Loop Or Arrays
Aug 26, 2004See Attachment
View 10 RepliesSee Attachment
View 10 RepliesHi all,
New to MS-SQL. Is there any concept of arrays in MS-SQL. If yes, how to implement it and where can i find more information?
Thank you
Suresh
hi, i'm passing a string to a Stored procedure(sp).this is string is delimited, say,
mon:tue:wed..is there a way in a sp to parse this string out an store it in an array and then use a for i=i to..whatever.. loop to access each element?
thanks
rohit
Is there any way to mimic the functionality of a dynamic array using T-SQL?
View 13 Replies View RelatedI have data I am retrieving using a datareader...and SQLSERVER
It could return 1 row of information or perhaps 3 rows of information
I need to know how to use an array here I would guess so I can access each element in this row or rows.
HOw might I use reader.read and get it into the array
I am creating an application for booking events. Each event has several dates and each date has a fixed amount of available seats.
Currently in the events table I have a field for the number of available seats and a field for the string of dates that are later parsed into a listbox control.
The problem with my current setup is each date is sharing the same number of available seats so if date Event A is decemented 10 so will Event B.
I need some way to associate each date with it's own number of available seats. What is the best way to do this? An array? If so how do I store an array in the DB?
Thanks, Justin.
Hi,
I'm a complete newbie to SQL, and I need to know if there's an easy way to do this....I'm working with PHP, and it uses the following SQL statement:
$query = mysql_query("INSERT INTO `databaseName_tags`.`data` (`order` ,`name` ,`rating` ,`info` ,`comment` ,`comment2`)
VALUES ('0','abc','5','helllo','great work','woohooo')");
But what I'd prefer to do, is to have two arrays like so:
$cols = array("order" ,"name" ,"rating" ,"info" ,"comment","comment2");
$data = array("0","abc","5","helllo","great work","woohooo");
$query = mysql_query("INSERT INTO `databaseName_tags`.`data` ($cols) VALUES ($data)");
Is it possible to do it something like what is given above? It'd make the program so much more flexible....
Hi;I have been writing a lot of short tsql scripts to fix a lot of tinydatabase issues.I was wondering if a could make an array of strings in tsql that Icould process in a loop, something likearray arrayListOfTablesToProcess = { "orders", "phone","complaints"}for( int i = 0; i < arrayListOfTablesToProcess.length; i++ )delete from arrayListOfTablesToProcess[i]Can you do something like this in tsql?I should probably stop asking all of these questions.Is there a good book on TSQL alone ( I'm not interested in wizards,just scripting )...that is short?Steve
View 2 Replies View Related Hi everyone
My stored procedure accepts 2 parameters: names, number of names like this: (name1, name2, name3,3) Problem is: the number of names changes each time i want to run it. Some time it is: Name1,1 and other time it is: name1, name2,2. So every time i run it i need to change code. I thought "arrays" might solve that problem but i never met arrays in sql2005. Does it exist ? Case answer is "no": What is it to replace arrays and solve the above problem?
Thanks
I'm have a stored procedure that iterates through a list of numbers and adds an item for each number (user id) some of these ids are duplicates which is fine even necessary for the first part of my query but for the last I need to ensure that no duplicates id's are passed to the stored procedure, in this case called 'spInsertForBackupNote'. My thoughts here was to do something like this:
SET @Note_Buffer = @UserID -- @Note_Buffer being some kind of array?
IF @Note_Buffer = @UserID -- If its been added to the buffer we dont execute sp
BEGIN
Do Nothing here
END
ELSE
BEGIN
EXECUTE spInsertForBackupNote @FK_UserID, @FK_NoteID
END
I know this would never work because it would always be false since I just added the same userid to the buffer that I want to add. But I think you see my problem. I know it should be an easy one but my TSQL is limited. I've posted the whole sp. Hope someone can help.
CREATE PROCEDURE spInsertAssignedNotesByList
@FK_UserIDList NVARCHAR(4000) = NULL,
@FK_NoteIDList NVARCHAR(4000) = NULL,
@By_Who INT,
@UserID INT
AS
SET NOCOUNT ON
DECLARE @Length INT
DECLARE @Note_Length INT
DECLARE @Note_Buffer INT
DECLARE @FirstUserIDWord NVARCHAR(4000)
DECLARE @FirstNoteIDWord NVARCHAR(4000)
DECLARE @FK_UserID INT
DECLARE @FK_NoteID INT
SELECT @Length = DATALENGTH(@FK_UserIDList )
SELECT @Note_Length = DATALENGTH(@FK_NoteIDList )
DECLARE @TempFK_NoteIDList NVARCHAR(4000) --= NULL
DECLARE @Temp_NoteLength INT
SET @TempFK_NoteIDList = @FK_NoteIDList
SET @Temp_NoteLength = DATALENGTH(@FK_NoteIDList )
-- IF @Length > @Note_Length -- If we have more users than notes
BEGIN
WHILE @Length > 0
BEGIN
IF @Length > 0
EXECUTE @Length = PopFirstWord @FK_UserIDList OUTPUT, @FirstUserIDWord OUTPUT
SELECT @FK_UserID = CONVERT(INT, @FirstUserIDWord)
IF @Length > 0
BEGIN
SET @FK_NoteIDList = @TempFK_NoteIDList
SET @Note_Length = @Temp_NoteLength
WHILE @Note_Length > 0
BEGIN
EXECUTE @Note_Length = PopFirstWord @FK_NoteIDList OUTPUT, @FirstNoteIDWord OUTPUT
SELECT @FK_NoteID = CONVERT(INT, @FirstNoteIDWord)
IF @Note_Length > 0
EXECUTE spInsertAssignedNoteDetail @FK_UserID, @FK_NoteID
SET @Note_Buffer = @UserID
EXECUTE spInsertForBackupNote @FK_UserID, @FK_NoteID, @By_Who, @UserID -- NEW HERE
END
END
END
END
--------------------------------------------------
GO
Can any one help me with a sample code, which can take an array of
elements as one of it's parameters and get the value inserted into a table in a
stored procedure.
Thanks in advance
vnswathi.
I want to pass my stored proc a list, and either loop through it as a list or (better) turn it into an array and loop through it that way to insert it. Psuedocode would be...
Loop from 0 to ListLength
begin
INSERT Transaction_Data
end
Thanks from an SQLS7 newbie,
jE
I'm newer to MS SQL, but have a programming background, so I'm going to try to describe what I'm doing in that sense.
What I want to do is pull an entire column of data from one table, and insert it into a column in another table. Typically, I would do this with an array and while loop or something similar. I've figured out how to do a while loop in SQL, but the array situation has me stumped. I tried reading http://weblogs.sqlteam.com/jeffs/archive/2007/06/26/60240.aspx that article, however it referred to a procedure, and I have no background or experience with procedures.
Any sort of idea or document on a technique to do this would be most appreciated, thank you!
I am glad to announce that there is now a version of my article "Arrays andLists in SQL Server" for SQL 2005 available on my web site.THe URL for the article ishttp://www.sommarskog.se/arrays-in-sql-2005.html. If you are curious aboutthe performance numbers they are in an appendix athttp://www.sommarskog.se/arrays-in-sql-perftest.html.The old version of the aritlce remains, as the new article covers SQL 2005only. The old version is now athttp://www.sommarskog.se/arrays-in-sql-2000.html.The old URL, http://www.sommarskog.se/arrays-in-sql.html leads to a pagethat links to both articles.And the reason that there are two articles is simply that SQL 2005 addsso many new features: nvarchar(MAX), the CLR, the xml data type, CTE thatall can be used in the realm of arrays and lists.--Erland Sommarskog, SQL Server MVP, Join Bytes!Books Online for SQL Server 2005 athttp://www.microsoft.com/technet/pr...oads/books.mspxBooks Online for SQL Server 2000 athttp://www.microsoft.com/sql/prodin...ions/books.mspx
View 1 Replies View RelatedHi,
I'm using Visual Studio and Visual Basic to save data about members in a database.
I use SQL-database as it's included.
However, I'm new to this saving in the datbase and wonder how I can at the best save data about a member without having to index each value in the arrays:
The array has 2 index and is declared
dim Results(6, 50) as string
Of course, I can do results11, results12,... results150, results21, ...results250....
But it seems rather awkward to do it this way. I'm sure that there is a better way.
Thanks, any assistance is appriciated!
Best wishes, Per
My sql-string looks like this:
SelectCommand="SELECT * FROM Table1 WHERE Field1 IN @target"
And my parameter looks like this:
<asp:ControlParameter Name="target" ControlID="CheckBoxList1" PropertyName="SelectedValue" />
This code gives me a syntax error near @target. Someone got a solution?
Dear all,
i want to know how i can pass multiple values in the form of arrays to a stored procedures.
the technique by which i pass multiple values to a stored procedure beginning along with declarations are as follows:
Dim configurationAppSettings As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader()
Me.cmdInsSlabHmst = New System.Data.OleDb.OleDbCommand()
Me.OleDbConnection1 = New System.Data.OleDb.OleDbConnection()
Me.cmdInsSlabDMst = New System.Data.OleDb.OleDbCommand()
'
'cmdInsSlabHmst
'
Me.cmdInsSlabHmst.CommandText = "PKGSLABHMST.INSSLABHMST"
Me.cmdInsSlabHmst.CommandType = System.Data.CommandType.StoredProcedure
Me.cmdInsSlabHmst.Connection = Me.OleDbConnection1
Me.cmdInsSlabHmst.Parameters.Add(New System.Data.OleDb.OleDbParameter("iSLABDESC", System.Data.OleDb.OleDbType.VarChar, 50))
Me.cmdInsSlabHmst.Parameters.Add(New System.Data.OleDb.OleDbParameter("iSLABUNIT", System.Data.OleDb.OleDbType.VarChar, 1))
Me.cmdInsSlabHmst.Parameters.Add(New System.Data.OleDb.OleDbParameter("iREMARKS", System.Data.OleDb.OleDbType.VarChar))
Me.cmdInsSlabHmst.Parameters.Add(New System.Data.OleDb.OleDbParameter("iSLABFROM", System.Data.OleDb.OleDbType.VarChar))
Me.cmdInsSlabHmst.Parameters.Add(New System.Data.OleDb.OleDbParameter("iSLABRATE", System.Data.OleDb.OleDbType.VarChar))
Me.cmdInsSlabHmst.Parameters.Add(New System.Data.OleDb.OleDbParameter("iNOOFRECORDS", System.Data.OleDb.OleDbType.Integer))
'
'OleDbConnection1
'
Me.OleDbConnection1.ConnectionString = CType(configurationAppSettings.GetValue("ConnectionString", GetType(System.String)), String)
'Passing multiple values to the procedure with the help of ~ sign
Dim strCode As String
Dim i As Integer
'Dim dblSlabRate As Decimal
'Dim dblSlabFrom As Decimal
Dim strSlabRate As String
Dim strSlabFrom As String
Dim strSlabRateP As String
Dim strSlabFromP As String
Dim intCntr As Integer
'Me.cmdInsSlabHmst.Parameters("iSLABDESC").Value = txtSlabDesc.Text
'Me.cmdInsSlabHmst.Parameters("iSLABUNIT").Value = ddlSalbUnit.SelectedItem.Value
'Me.cmdInsSlabHmst.Parameters("iREMARKS").Value = txtRemarks.Text
'OleDbConnection1.Open()
'strCode = cmdInsSlabHmst.ExecuteScalar
'OleDbConnection1.Close()
For i = 0 To dgSlabDtl.Items.Count - 1
If i = dgSlabDtl.Items.Count - 1 Then
'dblSlabRate = CType(dgSlabDtl.Items(i).FindControl("txtSlabRate"), TextBox).Text
'dblSlabFrom = CType(dgSlabDtl.Items(i).FindControl("txtSlabFrom"), TextBox).Text
strSlabRate = CType(dgSlabDtl.Items(i).FindControl("txtSlabRate"), TextBox).Text
strSlabFrom = CType(dgSlabDtl.Items(i).FindControl("txtSlabFrom"), TextBox).Text
Else
'dblSlabRate = CType(dgSlabDtl.Items(i).FindControl("lblSlabRate"), Label).Text
'dblSlabFrom = CType(dgSlabDtl.Items(i).FindControl("lblSlabFrom"), Label).Text
strSlabRate = CType(dgSlabDtl.Items(i).FindControl("lblSlabRate"), Label).Text
strSlabFrom = CType(dgSlabDtl.Items(i).FindControl("lblSlabFrom"), Label).Text
End If
strSlabRateP += strSlabRate & "~"
strSlabFromP += strSlabFrom & "~"
intCntr += 1
'If dblSlabRate <> "" And dblSlabFrom <> "" Then
'InsDtl(strCode, dblSlabFrom, dblSlabRate)
'End If
Next
If strSlabRateP <> "" And strSlabFrom <> "" Then
With cmdInsSlabHmst
.Parameters("iSLABDESC").Value = UCase(txtSlabDesc.Text)
.Parameters("iSLABUNIT").Value = ddlSalbUnit.SelectedItem.Value
.Parameters("iREMARKS").Value = txtRemarks.Text
.Parameters("iSLABFROM").Value = strSlabFromP
.Parameters("iSLABRATE").Value = strSlabRateP
.Parameters("iNOOFRECORDS").Value = intCntr
End With
OleDbConnection1.Open()
cmdInsSlabHmst.ExecuteNonQuery()
OleDbConnection1.Close()
End If
to the insert procedure i am passing multiple values with the help of ~ sign and in the procedure the individual values are separated by identifying the position of ~ sign and the no. of records which have been passed. For which a complicated stored procedure has been written.
i want to pass multiple values in an array, so that my stored procedure becomes simple and runs faster. So, if someone tells me how to pass arrays to a stored procedure (with code example), it will be of real help.
regards
subhajit
Someone recently tried to tell me that it is possible to pass an array to a stored procedure.
I have tried creating procedures with the 'table' datatype for the parameters but the attempts fail with a syntax error.
We currently workaround this limitation by passing the equivalent of an array to temporary tables and selecting from those tables as needed within our stored procedure but if we can circumvent this by passing an array, we'd definetly like to try that instead.
Thanks in advance for any advice you may share.
Hello,
My SQL knowledge is limited so if I get stuff wrong then correct me... but I can imagine this task will be quite testing...
I am working on a system that logs ([Audit] table) the changes to fields on some tables using a Trigger on UPDATE. I need to produce a 'quick' report that returns the date when the tables overallStatus field was set to 1.
In the [Audit] table I can find all the field changes for the record in question using this SQL...
select *
from audit
where rowid = 1309606
order by auditID asc
My problem is filtering this data. The fields I need are formatted as below, see records returned, in ASC order...
audit.AuditID = 2652583
audit.OperationTime = 2008-04-24 15:12:07.740
audit.ColumnDetail = 'estimatedProductionPriceactualProductionCost'
audit.EditDetail = '0.00000.0000'
audit.AuditID = 2658460
audit.OperationTime = 2008-04-25 10:51:47.930
audit.ColumnDetail = 'overallStatusInsertionStatus'
audit.EditDetail = '05'
audit.AuditID = 2665723
audit.OperationTime = 2008-04-25 22:06:50.200
audit.ColumnDetail = 'overallStatusdespatchDateInsertionStatus'
audit.EditDetail = '1Â 3'
audit.AuditID = 2711092
audit.OperationTime = 2008-04-30 17:22:12.593
audit.ColumnDetail = 'overallStatusInsertionStatus'
audit.EditDetail = '34'
audit.AuditID = 2713217
audit.OperationTime = 2008-04-30 20:46:34.817
audit.ColumnDetail = 'clientOrderNumber'
audit.EditDetail = 'PAT12P7640'
The funny character, , is ASCII 127.
So need to find when 1309606's overallStatus was changed to 1. Manually looking at the data, I can see overallStatus was modified in 3 of the above 5 [Audit] records. It started life as 0, then went to 1 and then to 3. I'm aware that I need to look at the previous Audits date for when it was changed to the value I'm looking for... So it was changed to 1 on 2008-04-25 10:51:47.930.
What is the best way to approach this problem? I'm hoping to use T-SQL only and not have to use an external scripting language, unless I can embed vbscript or jscript inside a T-SQL function and then use arrays, etc?
Somehow I need to convert the ASCII(127) seperated list of fieldname into an array or list, find the index of the fieldname 'overallStatus' and then lookup that value in the datafield.
Hope that makes sense and any help would be great!
Cheers,
Nick
How do you all recommend storing ordered pairs in SQL Server 2005? I plan to add one record for every data point but this will generate many records and requires an extra field to relate the points together. Are there any better ways to do this? Can the data still be searchable or does it have to be unpacked first?
View 2 Replies View RelatedI'm getting ready to install SQL Server 2005 Enterprise for the first time and I have a question about the directory location of the log files and the data files. I have 3 RAID arrays on my server, 1 for the OS, 1 for SQL Logs, and 1 for SQL Data.
Here's my issue. I want to install the logs on the Log array and the SQL data on the SQL data array, however, during the installation I can't find anything that allows me to select certain directories!
Am I missing something somewhere?
Thanks
I have a bunch of SPs that all rely on a UDF that parses a commadelimitted list of numbers into a table. Everything was working fine,but now my application is growing and I'm starting to approach the 8000character limit of the varChar variable used to store the list.I would like to change the UDF only and avoid having to dig through allof my stored procedures. I was hoping to use the text datatype toallow for much larger lists, but I am unable to perform anymanipulations necessary to parse the list into a table. I have triedPATINDEX, but it alone is not enough without the text maniuplations andI don't think the sp_xml_preparedocument can be used in a UDF.Anyone with any thoughts on managing large arrays in t-sql?thanks,Matt Weiner
View 2 Replies View RelatedHi
I know that SQL Server itself does not support passing arrays to its procedures. But I need an alternative that will allow me to "duplicate" the same functionality.
I have the following information stored in a Class:
1. Userid varchar(16)
2. SessionId varchar(50)
3. LoginTime datetime
4. UserHostAddress varchar(15)
5. UserAgent varchar(150)
6. Browser varchar(255)
7. Crawler varchar(20)
8. SessionURL varchar(255)
9. SessionReferer varchar(255)
10. VisitNumber int
11. OriginalReferer varchar(255)
12. OriginalUR varchar(255)
13. Pages Array List (PageName varchar(255), ElapsedTime datetime)
I have two tables :
UserInfo: Where I keep the variables 1-12
PageInfo: Where I keep variable 13 (the list of pages)
I need to store this information in my SQL Server Database. So far I found three possible methods but I'm not sure which one has the better performance:
First Method: the easy one
1. Call the SaveUserInfo stored procedure
2. Loop through the pages array and call the SavePageInfo stored procedure for each page item in the array
Second Method: Passing a delimited string to the stored procedure
1. Call the SaveUserInfo stored procedure
2. Pass a delimeted string to the SavePageInfo stored procedure. The stored procedure will split the string and save the pages into the database. The string would look like this:
PageAddress1-ElapsedTime1|PageAddress2-ElapsedTime2|PageAddress3-ElapsedTime3...
Third Method: Passing and XML File to the stored procedure
The stored procedure will read the XML file and store the information into the database.
What method is the best for performance?? As you may see this is for tracking the user navigation through the website. For the first method I worry about the number of call to the database; for the Second and Third method I worry about the lenght of the string or XML file to pass to the stored procedure.
Any suggestions??
Thanks for any help
Sasa
Hello All,
I have a 2-node cluster environment & I am planning to replace it with new hardware. Currently I am using MSA1000 Disk arrays. Now I would like to move my storage to SAN.
What are the necessary pre-requisite and actions to do this. Any particular thing, I must take care in planning.
Any help would be appreciated.
Thanks
Dev
difference between FOR LOOP and FOREACH LOOP with example(if possible) in SSIS.
View 4 Replies View RelatedI have a table with RowID(identity). I need to loop though the table using RowID(not using a cursor). Please help me.
Thanks
I have a foreach loop that is supposed to loop through a recordset, however it doesn't loop. It just repeats the same row, row after row.
I would like to look into the recordset variable but I can't because it is a COM object and the ADODB namespace is not available in the script task.
Any solution to this? anyone experienced anything similar
I have a table called Tbltimes in an access database that consists of the following fields:
empnum, empname, Tin, Tout, Thrs
what I would like to do is populate a grid view the a select statement that does the following.
display each empname and empnum in a gridview returning only unique values. this part is easy enough. in addition to these values i would also like to count up all the Thrs for each empname and display that sum in the gridview as well. Below is a little better picture of what I€™m trying to accomplish.
Tbltimes
|empnum | empname | Tin | Tout | Thrs |
| 1 | john | 2:00PM | 3:00PM |1hr |
| 1 | john | 2:00PM | 3:00PM | 1hr |
| 2 | joe | 1:00PM | 6:00PM | 5hr |
GridView1
| 1 | John | 2hrs |
| 2 | Joe | 5hrs |
im using VWD 2005 for this project and im at a loss as to how to accomplish these results. if someone could just point me in the right direction i could find some material and do the reading.
I have source and destination table names in the database(one table) and I need to read the source and destination tables one by one...
My Lookp table is like the following...
Srn srctable desttable
1 SRC1 DEST1
2 SRC2 DEST2
3 SRC3 DEST3
Now I want one package to load from source to destination.. how do I do it.. I dont know how to use....
How do I run the pacakge for each of the rows... ..............................
Hi all,
Ok here goes,
I have a three tier system using SQL server 2000, we are currently experiencing IO bottle necks on our SCSI Raid 10 array, which holds the Data and the logs in separate partitions.
So my options as I understand it are:
Get Enterprise edition
or
Get another physical raid 10 array and separate the logs and data i.e. data on one array and logs on the other array.
I would like to try the latter but I am totally unsure how much difference this will make or whether it will make any difference at all.
Does anyone know how much performance increase I will get from using two arrays as opposed to one?
Any other advice on this scenario would be greatly appreciated.
Thanks
I used to loop through recordsets with ease in old classic .asp pages.
Please Help me understand how Professionals now loop through and update tables using JUST SQL Query Analyzer using my pseudo-code provided below.
I would love to learn how to do it to better develop my skills.
SELECT * FROM zz_2007_Booth_Visitors
WHERE COALESCE ([Product Interest - Other Actuator],
[Product Interest - Chillers],
[Product Interest - Other Chiller],
[Product Interest - Electronic Products],
[Product Interest - Other network interfaces],
[Product Interest - Fittings],
[Product Interest - High Vacuum],
[Product Interest - Other high vacuum actuators],
[Product Interest - Pick& Place and Transfer],
[Product Interest - Teflon Products],
[Product Interest - Training],
[Product Interest - Valves& Manifolds],
[Product Interest - Actuators]) Is Not Null
Order BY [Contact Name]
IF [Product Interest - Actuators] IS NOT NULL THEN
UPDATE Booth_Visitors_Data Set Act_Phuematic = 1 Where [Contact Name] = [Contact Name]
IF [Product Interest - Other Actuator] IS NOT NULL THEN
UPDATE Booth_Visitors_Data Set Act_Electric = 1 Where [Contact Name] = [Contact Name]
IF [Product Interest - Other Chillers] IS NOT NULL THEN
UPDATE Booth_Visitors_Data Set Chiller = 1 Where [Contact Name] = [Contact Name]
Dear All.
Have a nice day.
I have db table, I need to update all fields of table.
Please can you write code," for loop " how can update all fields of my table by loop.
Thanks.
Zahyea.
Hello everyone,I've got this While loop here which is giving me a problem:WHILE (SELECT ProductId FROM _ShoppingCart WHERE CartId = @CartId) IS NOT NULLBEGIN DECLARE @ProdId int, @ProdSize varchar, @ProdQuan int SELECT @ProdId = ProductId, @ProdSize = ProductSize, @ProdQuan = Quantity FROM _ShoppingCart WHERE CartId = @CartId If @ProdSize = 'XL' BEGIN UPDATE _ProductBatches SET XL = '0' WHERE ProductId = @ProdId END DELETE FROM _ShoppingCart WHERE ProductId = @ProdId AND CartId = @CartIdEND The problem is that the IF statement isn't being executed. And I know for a fact that 'XL' is ProductSize in my _ShoppingCart database. Whats even stranger is that my delete statement is being executed. So @ProdId is Being set correctly, but when it gets to the IF @ProdSize = 'XL' it doesn't get executed for some reason. If @ProdId is being recognized correctly in my DELETE statement, why is my @ProdSize not being reconized correctly in my IF statement. I checked my _ShoppingCart database, and my ProductSize is definitely 'XL'. Can any one see what could be going on here. Thank you, Alec
View 7 Replies View Related