SQL - Iterating through table records
sql, sql-server
Solution
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
Problem
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?