T-SQL loop over SQL Select query results
select @id=table.id from table and I need to loop over the results so I can exec a store procedure for each row exec stored_proc @varName=@id,@otherVarName='test'
How can I do this in a T-SQL script?
You could use a CURSOR in this case:
DECLARE @id INT
DECLARE @name NVARCHAR(100)
DECLARE @getid CURSOR
SET @getid = CURSOR FOR
SELECT table.id,
table.name
FROM table
OPEN @getid
FETCH NEXT
FROM @getid INTO @id, @name
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC stored_proc @varName=@id, @otherVarName='test', @varForName=@name
FETCH NEXT
FROM @getid INTO @id, @name
END
CLOSE @getid
DEALLOCATE @getid
Cursor is a database objects to retrieve data from a result set one row at a time, instead of the T-SQL commands that operate on all the rows in the result set at one time. We use cursor when we need to update records in a database table in singleton fashion means row by row.
Cursor Flow
Declare Cursor
A cursor is declared by defining the SQL statement that returns a result set.
Open
A Cursor is opened and populated by executing the SQL statement defined by the cursor.
Fetch
When cursor is opened, rows can be fetched from the cursor one by one or in a block to do data manipulation.
Close
After data manipulation, we should close the cursor explicitly.
Deallocate
Finally, we need to delete the cursor definition and released all the system resources associated with the cursor.
Syntax of Cursor
Declare Cursor SQL Comaand is used to define the cursor with many options that impact the scalablity and loading behaviour of the cursor. The basic syntax is given below
- DECLARE cursor_name CURSOR
- [LOCAL | GLOBAL] --define cursor scope
- [FORWARD_ONLY | SCROLL] --define cursor movements (forward/backward)
- [STATIC | KEYSET | DYNAMIC | FAST_FORWARD] --basic type of cursor
- [READ_ONLY | SCROLL_LOCKS | OPTIMISTIC] --define locks
- FOR select_statement --define SQL Select statement
- FOR UPDATE [col1,col2,...coln] --define columns that need to be updated
Syntax to Open Cursor
A Cursor can be opened locally or globally. By default it is opened locally. The basic syntax to open cursor is given below:
- OPEN [GLOBAL] cursor_name --by default it is local
Syntax to Fetch Cursor
Fetch statement provides the many options to retrieve the rows from the cursor. NEXT is the default option. The basic syntax to fetch cursor is given below:
- FETCH [NEXT|PRIOR|FIRST|LAST|ABSOLUTE n|RELATIVE n]
- FROM [GLOBAL] cursor_name
- INTO @Variable_name[1,2,..n]
Syntax to Close Cursor
Close statement closed the cursor explicitly. The basic syntax to close cursor is given below:
- CLOSE cursor_name --after closing it can be reopen
Syntax to Deallocate Cursor
Deallocate statement delete the cursor definition and free all the system resources associated with the cursor. The basic syntax to close cursor is given below:
- DEALLOCATE cursor_name --after deallocation it can't be reopen
No comments:
Post a Comment