Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Iterating through table records

Tags:

sql

sql-server

I have created user-defined function that converts a comma-delimited string into a table. I execute this function like so:

select [String] as 'ID' from dbo.ConvertStringToTable('1,2,3,4')

The results from this query look like the following:

ID
--
1
2
3
4

In reality, I want to iterate through each of the rows in this table. However, I cannot figure out how to do this. Can someone show me some sample SQL of how to iterate through the rows of the table?

like image 736
user255048 Avatar asked Feb 05 '10 12:02

user255048


2 Answers

In SQL SERVER 2000/05/08 you can use a Cursor as shown below.

However before you go down the cursor path you should first look into the problems associated with cursors in SQL Server.

DECLARE @id VARCHAR(10)

DECLARE myCursor CURSOR LOCAL FAST_FORWARD FOR
    SELECT [String] AS 'ID' 
    FROM [dbo].[ConvertStringToTable]('1,2,3,4')
OPEN myCursor
FETCH NEXT FROM myCursor INTO @id
WHILE @@FETCH_STATUS = 0 BEGIN
    PRINT @id
    -- do your tasks here

    FETCH NEXT FROM myCursor INTO @id

END

CLOSE myCursor
DEALLOCATE myCursor
like image 85
Kane Avatar answered Sep 22 '22 23:09

Kane


Don't use the cursor if you can avoid it, normally all you really need is to join to the table that you created. If your cursor is doing an update, insert, or delete, you have a 99.9% chance of not needing a cursor. Cursors should be a technique of LAST resort not first resort. Iterating through records is almost always a poor choice in a database. Learn to think in sets.

Why should you avoid cursors? Becasue they create performance nightmares. I've changed processes from taking 24 hours or more to less than a minute by removing the curosr.

like image 25
HLGEM Avatar answered Sep 25 '22 23:09

HLGEM