Retrieving SQLQuery Results In Array On C#--How???

Apr 9, 2008

 Hi I'am practically new in C#, so I want to ask you guys some question.
Let say I have this query:
"Select EmployeeID, EmpName from PI_Employee"
How can I retrieve the result from EmployeeID column and EmpName column and put it into collections of array, so I can call the array and use it again in another function. Can I possibly do that in C# ? if so, how ? please help me guys, I'm on the edge of nervous wreck in here so I could use a little help, any kinds of help. Thanks.
 
Best Regards. 

View 9 Replies


ADVERTISEMENT

Retrieve SQLQuery Result In Array On C#--How ????

Apr 9, 2008

 Hi I'am practically new in C#, so I want to ask you guys some question.Let say I have this query:"Select EmployeeID, EmpName from PI_Employee"How can I retrieve the result from EmployeeID column and EmpName column and put it into collections of array, so I can call the array and use it again in another function. Can I possibly do that in C# ? if so, how ? please help me guys, I'm on the edge of nervous wreck in here so I could use a little help, any kinds of help. Thanks. Best Regards. 

View 2 Replies View Related

Filling A DataTable From SqlQuery : If SqlQuery Returns Null Values Problem Ocurrs With DataTable

Sep 3, 2007

Filling a DataTable from SqlQuery : If SqlQuery returns some null values problem ocurrs with DataTable.
Is it possible using DataTable with some null values in it?
Thanks

View 2 Replies View Related

Database Results Stored In A Array

Jul 22, 2004

How would I go about storing (1 column) database results in a Array?

And then how would I go about extracting the elements from the Array?

View 4 Replies View Related

Results To String Array For Reference Within CLR Proc

Jun 13, 2006

I keep running into a problem with the debugger freezing up. I'm trying to pull results from a query into an array (not more than 10 rows)

cmd.ExecuteReader();

while (rdr.Read() == true) {

letter = rdr[0].ToString();

i += 1;

}



if I comment out the "letter = rdr[0].ToString();" portion of code, the project runs fine. With that code there, I can not step into the proc from the SQL test script. No errors are raised. VS just freezes.

View 1 Replies View Related

Help In Retrieving Results

Oct 11, 2005

i have a table in MS SQL Server,i need to show two results at a time,and on click of a button nxt two results have to b shown,how do i accomplish this (i mean retrieving the results two at a time)thanx in advance

View 1 Replies View Related

Retrieving Max Date Results

Sep 16, 2013

What is the easiest way to get the premium rate for this particular merchant

I am only interested in knowing what the rate was in july,

SELECT [FDMSAccountNo]
,[fee_sequence]
,[fee_retail_amt]
,[fee_wholesale_date]
,[fee_retail_date]
,max([fee_retail_date])

[Code] ....

Currently results return

FDMSAccountNo fee_sequence fee_retail_amt fee_wholesale_date fee_retail_date (No column name)
878756470885 7EK 0.00960000 2013-05-28 2013-05-28 2013-05-28
878756470885 7XC 0.00990000 2013-05-28 2013-05-28 2013-05-28
878756470885 7EK 0.00960000 2013-02-27 2013-02-27 2013-02-27
878756470885 7XC 0.00990000 2013-02-27 2013-02-27 2013-02-27

View 1 Replies View Related

Problem In Retrieving Query Results

May 14, 2008

 HI y'all, I have a problem in my query I hope you dudes can help. Ya see I have this query:SELECT CustId,CustName,CustAddress,CreditLimit,dateStart,DateUpdated From AR_Customer And this is the resultsCustId       CustName         CustAddress                CreditLimit              dateStart                                    DateUpdated-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------CS0201    Reena                Mayfield Str.                300000.000            2006-08-01 00:00:00.000              2006-08-01 00:00:00.000 CS0202    Bryant                Bringfield 202               50000.000             2006-08-01 00:00:00.000              2006-08-01 00:00:00.000CS0203    Jack                   Marjory 22                   3000000.000         2006-08-01 00:00:00.000              2007-05-18 17:30:23.000CS0204    Alan                   Orchard 25                   4500000.000        2006-10-02 00:00:00.000              2006-08-01 00:00:00.000Then I add Where clause to the query, like this  SELECT CustId,CustName,CustAddress,CreditLimit,dateStart,DateUpdated From AR_Customer WHERE DateUpdated = '08/01/2006'And the  result is just as I expected:CustId       CustName         CustAddress               
CreditLimit              dateStart                                   
DateUpdated
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------CS0201   
Reena                Mayfield Str.                300000.000           
2006-08-01 00:00:00.000              2006-08-01 00:00:00.000 CS0202
   Bryant                Bringfield 202               50000.000       
     2006-08-01 00:00:00.000              2006-08-01 00:00:00.000CS0204    Alan                   Orchard 25                  
4500000.000        2006-10-02 00:00:00.000              2006-08-01
00:00:00.000But when I changed the date parameter to 05/18/2007 for example like this SELECT CustId,CustName,CustAddress,CreditLimit,dateStart,DateUpdated From AR_Customer WHERE DateUpdated = '05/18/2007'It doesn't show any results at all, it just showing the header CustId       CustName         CustAddress               
CreditLimit              dateStart                                   
DateUpdated
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------What I want  to ask is why is that happen, is it because the date contains hours--according to the database is the date contain hours like this 2007-05-18 17:30:23.000. I already use this operator <=,>= but it just showing the wrong result. Can you guys tell me the correct query, please. I appreciate any help. Thanks. FYI: I use SQL Server 2000Best Regards.  

View 4 Replies View Related

RS2005: Export To Excel Error: Destination Array Was Not Long Enough. Check DestIndex And Length, And The Array's Lower Bounds.

Jan 25, 2007

All,

I am using Reporting Services 2005. One of my reports is getting the following error when I try to export to Excel. It will export to .CSV though.

"Destination array was not long enough. Check destIndex and length, and the array's lower bounds."

Any suggestions would be greatly appreciated. Please copy me at machelle.a.chandler@intel.com.

Machelle

View 10 Replies View Related

SQLQUERY

Mar 7, 2008

Hi,Here is my SQL Query.SQL = "insert into mnetwork..tblContactCorr(CorrespondentID,Name,Phone,Fax,Email,UserName,rowguid,Status,ChgPassword,lastlogin,MailNotification,USerLevel,LocationID,msrepl_tran_version)"SQL = SQL & " values( '" & drpCorr.SelectedValue & "', '" & txtName.Text & "', '" & txtphone.Text & "', '" & txtFax.Text & "', '" & txtEmail.Text & "', '" & txtUserName.Text & "', '" & mGuid & "', '" & drpstatus.SelectedValue & "', '" & "Null" & "', '" & getdate & "', '" & drpmn.SelectedValue & " ', '" & drpuserlevel.SelectedValue & "', '" & drplocation.SelectedValue & "', '" & "Null" & "')"Dim dbcommand As New SqlCommand(SQL, ObjConn)ObjConn.Open()dbcommand.ExecuteNonQuery()------>here is the problemdbcommand = New SqlCommand("select @@identity", ObjConn)Dim NewUserID = dbcommand.ExecuteScalarAfter executing i am getting error like this:Message "Syntax error converting from a character string to uniqueidentifier." StringI don't know how to convert mguid into uniqueidentifier.here is my batabase fields:ContactID-->this is auto incrementCorrespondentID--intName-varcharPhone-varcharFax-varcharEMail-varcharUserName-varcharrowguid--uniqueiduntifierstatus-tiniintchgpassword-snallintlastlogin--datetimemailnotification--smallintlocationid--intmsrepl_tran_version-uniqueiduntifier -(this is null)let me know whats wrong in this?

View 8 Replies View Related

How Would I Send A String Array As A Integer Array?

Jun 25, 2007

I have a stored procedure that has a paramter that accepts a string of values. At the user interface, I use a StringBuilder to concatenate the values (2,4,34,35,etc.) I would send these value to the stored procedure. The problem is that the stored procedure doesn't allow it to be query with the parameter because the Fieldname, "Officer_UID" is an integer data type, which can't be query against parameter string type.
What would I need to do to convert it to an Integer array?
@OfficerIDs as varchar(200) 
Select Officer_UID From Officers Where Officer_UID in (@OfficerIDs)
 Thanks

View 5 Replies View Related

Parametres - SqlQuery

Jun 22, 2007

Could you pls let me know that when we use the parameters how the sql server ıs able to keep all the datas on the strıng type?and also how ıt can be provıde that securıty on system(how ıt ıgnore to do sql ınjectıon...).

View 1 Replies View Related

Get Excel File When Run Sqlquery

Dec 23, 2007

Hi All
im using sqlserver2005 and i have sqlquery to get some fileds
now  i need to get out put in excel file when i run sqlquery
can anyone explain me how can i do it...this is my query
select ta_targetpath from tblattributes where ta_pagelevel = 2 and ta_description like '%Do you want to watch this configuration in action%'
and ta_targetpath is not null
when i execute this i need to get result set in excel file...
thnx in advance
Hary

View 1 Replies View Related

Sqlquery Or Storedprocedure Error

Jun 18, 2008

Hello everyone,I am developing forums (Discussion Board) in C#.net 2005 with SqlServer. Right now i am having problem in fetching data from two tables.Here are the tables from which i want to fetch data.Topics Table                                  Threads TableTopicID                                          ThreadIDForumID                                        TopicIDTopicName                                    SubjectTopicDescription                            Replies                                                    UserID                                                    LastPostDatenow i want to fetch all the topic talbe data as well as total no of threads,Lastpostdate,UserID per topic.I am able to fetch  topic table data  and  Total no of  threads per topic through the following query.SELECT TopicID, ForumID, TopicName, TopicDescription,(SELECT COUNT(ThreadID)  FROM Portal_Threads WHERE (TopicID = Portal_Topics.TopicID)) AS Threads FROM Portal_Topicsbut i am not able to fetch anoter two detail with subquery as i am getting error likeonly one expression can be specified in the select listorsubquery returned more than one value.can anyone tell me how can i fetch these two values per topic. should i use stored procedure and create temporary table and after fetching these values i can store it in temporary table and i can fetch values from that temporary table...please provide code snippet if possible as i've never used sqlserver before..Thanks in advance...Regards,Nil 

View 8 Replies View Related

SQLquery Using Parameter Help Needed Please C#???

Aug 14, 2004

Hi All,

I'm trying to pass in a parameter value from an array in a loop that is used in a sql query and the results are populated to an xml file. The trouble is that I'm only getting the colums values in the outputted xml file. So I feel that the paramter is not being read.

So can anyone help as I'm really stuck on this one. The code is as follows :

public void DisplayUserInfo()
{

ArrayList UserIdArrayList = IdentifyUserID();
foreach(string ShowUserIDString in UserIdArrayList)
{
try
{
SqlConnection SqlConn = new SqlConnection(DBConnString);
SqlConn.Open();
Console.WriteLine("Connected to DB");
SqlDataAdapter SqlAD = new SqlDataAdapter();
SqlAD.SelectCommand = new SqlCommand("Select * from UserSystemSpecs where UserName ='+ShowUserIDString.ToString()+'",SqlConn);
DataSet ds = new DataSet();
SqlAD.Fill(ds);
ds.WriteXml(".\ResultsXML.xml", XmlWriteMode.WriteSchema);
}

catch (Exception ex)
{
throw new Exception ("Error Connecting to DB. " + ex.Message);
}
//SqlConn.Close();


}

}


Thanks

Garry

View 2 Replies View Related

Insert DEFAULT When Getting Values From A SQLquery

Nov 16, 2006

I have a this SP that inserts values into a table with results from a query, but at the same time I want to insert some default values.But thats NOT working the way I hoped for, actually sqlserver 2005 dont let me create this SP at all."Incorrect syntax near the keyword 'DEFAULT'."Can someone please tell me how I can achieve this? create procedure %PROC% ( @Ordre_ID int
)
asbeginIF NOT EXISTS(SELECT Ordre_ID FROM tbl_Ordre WHERE Ordre_ID = @Ordre_ID AND Ordrestatus IN ('2', '3', '4'))BEGIN return 0;ENDIF EXISTS(SELECT Ordre_ID FROM tbl_Faktura WHERE Ordre_ID = @Ordre_ID)BEGIN return 0; ENDBEGIN TRANSACTIONINSERT INTO tbl_Faktura( Ordre_ID ,PostNummer ,KID ,Fakturastatus ,Kontonummer ,Forfallsdato ,Belop ,BekreftetBetaltDato ,Faktura_GUID ,Adresse ,PostBoks ,Fornavn ,Etternavn ) (SELECT O.Ordre_ID ,K.PostNummer ,DEFAULT
,DEFAULT
,SI.Kontonummer
,(getdate()+14) ,v_OTS.TOTALBELOP ,DEFAULT
,DEFAULT
,K.Adresse
,K.PostBoks
,K.Fornavn
,K.Etternavn
FROM
tbl_Ordre AS O INNER JOIN
tbl_Kunde AS K ON
O.Kunde_ID = K.Kunde_ID
INNER JOIN
v_OrdreTotalSum AS v_OTS ON
O.Ordre_ID = v_OTS.Ordre_ID
,tbl_StatiskeInnstillinger AS SI WHERE
O.Ordre_ID = @Ordre_ID
)
UPDATE
tbl_Ordre
SET
Ordrestatus = '6'
WHERE Ordre_ID = @Ordre_ID COMMIT end
go
 

View 3 Replies View Related

Is There A Way To Hold The Results Of A Select Query Then Operate On The Results And Changes Will Be Reflected On The Actual Data?

Apr 1, 2007

hi,  like, if i need to do delete some items with the id = 10000 then also need to update on the remaining items on the with the same idthen i will need to go through all the records to fetch the items with the same id right?  so, is there something that i can use to hold those records so that i can do the delete and update just on those records  and don't need to query twice? or is there a way to do that in one go ?thanks in advance! 

View 1 Replies View Related

SQL Server 2008 :: Elegant Way For Returning All Results When Subquery Returns No Results?

Mar 25, 2015

I have four tables: Customer (CustomerId INT, CountyId INT), County (CountyId INT), Search(SearchId INT), and SearchCriteria (SearchCriteriaId INT, SearchId INT, CountyId INT, [others not related to this]).

I want to search Customer based off of the Search record, which could have multiple SearchCriteria records. However, if there aren't any SearchCriteria records with CountyId populated for a given Search, I want it to assume to get all Customer records, regardless of CountyId.

Right now, I'm doing it this way.

DECLARE @SearchId INT = 100
SELECT * FROM Customer WHERE
CountyId IN
(
SELECT CASE WHEN EXISTS(SELECT CountyId FROM SearchCriteria WHERE SearchId = @SearchId)
THEN SearchCriteria.CountyId

[Code] .....

This works; it just seems cludgy. Is there a more elegant way to do this?

View 4 Replies View Related

Need To Display Results Of A Query, Then Use A Drop Down List To Filter The Results.

Feb 12, 2008

Hello. I currently have a website that has a table on one webpage. When a record is clicked, the primary key of that record is transfered in the query string to another page and fed into an sql statement. In this case its selecting a project on the first page, and displaying all the scripts for that project on another page. I also have an additional dropdownlist on the second page that i use to filter the scripts by an attribute called 'testdomain'. At present this works to an extent. When i click a project, i am navigated to the scripts page which is empty except for the dropdownlist. i then select a 'testdomain' from the dropdownlist and the page populates with scripts (formview) for the particular test domain. what i would like is for all the scripts to be displayed using the formview in the first instance when the user arrives at the second page. from there, they can then filter the scripts using the dropdownlist.
My current SQL statement is as follows.
SelectCommand="SELECT * FROM [TestScript] WHERE (([ProjectID] = @ProjectID) AND ([TestDomain] = @TestDomain))"
So what is happening is when testdomain = a null value, it does not select any scripts. Is there a way i can achieve the behaivour of the page as i outlined above? Any help would be appreciated.
Thanks,
James.

View 1 Replies View Related

Stored Proc Results Are Displaying In The Messages Tab Instead Of Results Tab- URGENT

May 14, 2008




Hi All,
I have a stored proc which is executing successfully...but the results of that stored proc are displaying in the Messages Tab instaed of results Tab. And in the Results Tab the results shows as 0..So, Any clue friends..it is very urgent..I am trying to call this stored proc in my Report in SSRS as well but the stored proc is not displaying there also...Please help me ASAP..

Thanks
dotnetdev1

View 4 Replies View Related

Mind-boggling Gridview Results! Different Results For Different Teams..

Jun 18, 2008

Hi all, I have the following SQLDataSource statement which connects to my Gridview:<asp:SqlDataSource ID="SqlDataSourceStandings" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"  SelectCommand="SELECT P.firstName, P.lastName, T.teamName, IsNull(P.gamesPlayed, 0) as gamesPlayed, IsNull(P.plateAppearances,0) as plateAppearances, IsNull( (P.plateAppearances - (P.sacrifices + P.walks)) ,0) as atbats, IsNull(P.hits,0) as hits, P.hits/(CONVERT(Decimal(5,2), IsNull(NullIF(P.atbats, 0), 1))) AS [average], (P.hits + P.walks)/(CONVERT(Decimal(5,2), IsNull(NullIF( (P.atbats + P.sacrifices + P.walks) , 0), 1)))  AS [OBP], (P.hits - (P.doubles + P.triples + P.homeRuns) + (2 * P.doubles) + (3 * P.triples) + (4 * P.homeRuns)) / (CONVERT(Decimal(5,2), IsNull(NullIF(P.atbats, 0), 1))) AS [SLG], P.singles, P.doubles, P.triples, P.homeRuns, P.walks, P.sacrifices, P.runs, P.rbis FROM Players P INNER JOIN Teams T ON P.team = T.teamID ORDER BY P.firstName, P.lastName"></asp:SqlDataSource>There are 8 teams in the database, and somehow the average and obp results are as expected for all teams except where T.teamID = 1.  This doesn't make sense to me at all!  For example, I get the following results with this same query: First NameLast NameTeamGPPAABHAVGOBPSLG1B2B3BHRBBSACRRBI

BrianAustinHope83432230.7187500.7352941.15625014612201221

GabrielHelbigSafe Haven62119141.0000000.9375002.1428576404111519

MarkusJavorSafe Haven82927200.8695650.8000001.21739114501021218

RobBennettMelville83029240.8275860.8333331.55172411904102117

AdamBiesenthalSafe Haven82929210.9130430.9130431.56521712631001015

ErikGalvezMelville82625180.7200000.7307691.24000011322101015 As you can see, all teams except for Safe Haven's have the correct AVG and OBP.  Since AVG is simply H/AB, it doesn't make sense for Gabriel Helbig's results to be 1.00000. Can anyone shed ANY light on this please?Thank you in advance,Markuu  ***As a side note, could anyone also let me know how I could format the output so that AVG and OBP are only 3 decimal places? (ex: 0.719 for the 1st result)*** 

View 2 Replies View Related

Removing Individual Results From A Paged Set Of Results.

Oct 19, 2007

Hi,
I have a web form that lets users search for people in my database they wish to contact. The database returns a paged set of results using a CTE, Top X, and Row_number().
I would like to give my users to option of removing individual people from this list but cannot find a way to do this.
I have tried creating a session variable with a comma delimited list of ID's that I pass to my sproc and use in a NOT IN() statement. But I keep getting a "Input string was not in a correct format." Error Message.
Is there any way to do this? I am still new to stored procedures so any advice would be helpful.
Thanks
 

View 3 Replies View Related

PASTE SQL RESULTS INTO EXCEL - Funny Results

Jan 30, 2008

Hi, when I copy and paste results from query analyzer into Excel it appears that values with zeroes at the end loose the zeroes. Example, if I copy and paste V128.0 into an Excel cell it comes out as V128 or if I copy 178.70 it displays as 178.7 - any ideas? I'm using SQL Enterprise Manager for 2000.

View 6 Replies View Related

Array

Jul 17, 2007

how can i send array from asp.net to sql?

View 3 Replies View Related

Get Array Value From A Loop?

Jun 19, 2006

Hi, I am trying to do a loop while a list of array is assigned ('CHP,CNH,COW') ... I am using comma seperator to get each list value ... but, it donest really do what I am trying to do ... pls help!!! How do I loop through each value and do the rest ...??
=====================================
DECLARE @ABBR AS NVARCHAR(50)SET @ABBR = 'CHP,CNH,COW'
DECLARE @SEP AS NVARCHAR(5)SET @SEP = ','
 WHILE  patindex('%,' + @ABBR + ',%',  @ABBR ) > 0    BEGIN
   -- do the rest
END

View 1 Replies View Related

SQL Query In A VB.net Array

Jan 31, 2007

I want to do a query on an SQL Server 2005 db and have the results returned into aarray or collection in vb.net... how do I do this? I know the basicconnection and stuff.. just not how to get the result to an array thanks!

View 1 Replies View Related

Array Problem

Apr 4, 2007

Hi All,
I have this code below:Dim a As Integer = 0        While a <= myArray.Length()            Conn.Open()            Dim UpdateCmd As New SqlClient.SqlCommand("Update email_addr SET category = 'Deleted' where HP = @hp", Conn)            UpdateCmd.Parameters.Add("@hp", SqlDbType.VarChar, 50).Value = myArray(a)            UpdateCmd.ExecuteNonQuery()            a = a + 1            Conn.Close()        End While
BUt, When I run it, I receive error "Prepared statement '(@hp varchar(50))Update email_addr SET category = 'Deleted' wher' expects parameter @hp, which was not supplied.  "
DOes anyone have the solution???
Thanks....
 

View 1 Replies View Related

Array In WHERE Clause

Aug 28, 2007

 Hello, how can I use an array in a WHERE clause? If I had an array saystring[] NamesArray = new string[] {"Tom", "***", "Harry"} How would I do this:string myquery = "SELET name, city, country FROM myTable WHERE name in NamesArray" Thanks in advance,Louis 

View 3 Replies View Related

DataRow Array

Jan 16, 2008

Hi,
 i m pretty new to this forum and c#.net 
i m doin a project in c#.net
I have four values in my datarow array
for example
DataRow[] cmb;
cmb=dsResult.Tables[0].Select("Controls Like 'cmb%'");// Here i m getting four Rows
 
for(i=0;i<cmb.Length;i++)
{
cmb[i]=Session["cmb'+i].ToString().Trim()//Here i m getting error;Cannot implicitly convert type 'string' to 'System.Data.DataRow'
}
 
 How to assign my session values to them.
I want to assign my value stored in the session variable to that array.Is there any way i can do it.Can i convert datarow array to string array! Please can any one help
me.
 

View 6 Replies View Related

Parameterized Or Array With This SQL?

Jun 2, 2008

I have two CheckBoxList controls. One CheckBoxList is a group of area codes as they apply to our customers, and the second CheckBoxList is a group of categories of those customers. The code below works fine with either CheckBoxList as a standalone (this code applies to the Area Codes selection), but what I need is the VB code to combine the choices a user makes in both CheckBoxLists. Is this where parameterized SQL comes into play? Or can I/should I use an array statement to combine both CheckBoxList choices? Sometimes a user will select nothing in one CBL and a few choices in the other, or vice versa, or a handful of choices in both CBLs, so that they might want only customers in, say two area codes and then only the selected categories of those area codes.  Need help on this one, thanks...Protected Sub btn_CustomerSearchCombine_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_CustomerSearchCombine.Click        Dim ACSelections As Boolean = False        Dim ACItem As ListItem        For Each ACItem In cbl_CustomerSearchAREA.Items             If ACItem.Selected Then                ACSelections = True            End If        Next        If ACSelections = True Then            Dim ACSqlString As String            ACSqlString = "SELECT Customers.CustomerID, Customers.CustomerName, Customers.CategoryID, Customers.EstHours, Customers.Locality, Categories.Category FROM Customers INNER JOIN Categories ON Customers.CategoryID = Categories.CategoryID WHERE "            For Each ACItem In cbl_CustomerSearchAREA.Items                If ACItem.Selected Then                    ACSqlString &= "Customers.AreaCodeID = '" & ACItem.Value & "' OR "                End If            Next            ACSqlString = Left(ACSqlString, Len(ACSqlString) - 4)            ACSqlString &= "ORDER By Customers.CustomerName"            sql_CustomerSearchGrid.SelectCommand = ACSqlString        End IfEnd Sub 

View 7 Replies View Related

Result Set Into Array

Aug 22, 2004

Hi All,

How can I read a query result set (which are of type VARCHAR) into an array? i.e the result set comprises of just one column and 5 rows and i want to save these into an array to easily extract each row whenever i want to. Hope I have conveyed my idea clearly.

Gayathri

View 1 Replies View Related

SqlCommand Array Help

Feb 19, 2006

I want to do something like the following but I get an error: Object reference not set to an instance of an object.       SqlConnection sqlConnection = new SqlConnection("server=xxxxx");        SqlCommand [] cmd = new SqlCommand[3];        Object returnValue;          cmd[0].CommandText = "DO QUERY";          cmd[1].CommandText = "DO QUERY";          cmd[2].CommandText = "DO QUERY";          cmd[3].CommandText = "DO QUERY";        }        sqlConnection.Open();int i = 0;while(i<4){       cmd[i].CommandType = CommandType.Text;        cmd[i].Connection = sqlConnection;        cmd[i].ExecuteNonQuery();        returnValue[i] = cmd[i].ExecuteScalar();i++}        sqlConnection.Close();How should I do the followingThanks

View 9 Replies View Related

Inline Sql With An Array

Sep 20, 2006

I have data which looks like below

actid labname
100 CKS
200 CKS;HDP;LAS

I need the data to be

actid labname
200 CKS
200 HDP
200 LAS

The ; is the seperator

For a reporting product I created a sp which created a temp table and then using my function below built. problem is the product won't allow me to create a temp table. With what I have below anyone have any creative ideas I could use. In-line sql, subquery views?

select enc_id,labcnt,order_name,date_due


reate FUNCTION fn_GET_ARRAY_VALUE(
@DELIMITER VARCHAR(100),
@STRING VARCHAR(1000),
@ARRAY_POSITION INT)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @CURRENT_POSITION INT
DECLARE @VALUE VARCHAR(8000)
SET @CURRENT_POSITION = 0

WHILE @CURRENT_POSITION<@ARRAY_POSITION
AND CHARINDEX(@DELIMITER,@STRING,0)>0
BEGIN
SET @STRING =
SUBSTRING(@STRING,
CHARINDEX(@DELIMITER, @STRING, 0)
+LEN(@DELIMITER),
LEN(@STRING)
-CHARINDEX(@DELIMITER, @STRING, 0)
+ LEN(@DELIMITER)
)
SET @CURRENT_POSITION = @CURRENT_POSITION + 1
END

IF CHARINDEX(@DELIMITER,@STRING,0)=0
SET @VALUE = @STRING
ELSE
SET @VALUE = SUBSTRING(@STRING, 0,
CHARINDEX(@DELIMITER, @STRING, 0)
)

RETURN(LTRIM(RTRIM(@VALUE)))
END

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved