Many times developer ask me that How can they remove Cursor? They need to increase Query Performance, that's why they need to remove SQL SERVER Cursor and find the alternate way to accomplish the same. Please find this code to remove cursor with Table variable: --declare table to keep records to be processedDECLARE @Table AS TABLE(AutoID INT IDENTITY, Column1 VARCHAR(100), Column2 VARCHAR(100))--populate table variable with data that we want to processINSERT INTO @Table(Column1, Column2)SELECT Column1, Column2FROM <Table>WHERE <Conditions>--declare variables to process each recordDECLARE @inc INT, @cnt INT--Assign increment counterSELECT @inc = 1--Get Number of records to be processedSELECT @cnt = COUNT(*)FROM @TableWHILE @inc <= @cnt BEGIN--As we have AutoID declared as IDENTITY, it always get only one record.--Get values in Variable and process it as you want.SELECT @Column1 = Column1,@Column2 = Column2FROM @TableWHERE AutoID = @inc--do your calculation here........--Select next recordSET @inc = @inc = 1END By this way, we can remove CURSOR by Table variable. It is quite easy to implement. One more benefit is: It will process one record at a time, so it locks only that record at a time. Let me know if you have any questions. |
Learn SQL and database management at SQLYoga for articles, tutorials, and tips to improve your skills and streamline data operations. Join our community!
December 2, 2009
SQL SERVER: How to remove cursor
Labels:
Cursor,
Query Performance,
SQL Developer,
SQL Server 2005,
T-SQL,
Table Variable,
Tejas Shah
18+ years of Hands-on Experience
MICROSOFT CERTIFIED PROFESSIONAL (Microsoft SQL Server)
Proficient in .NET C#
Hands on working experience on MS SQL, DBA, Performance Tuning, Power BI, SSIS, and SSRS
Subscribe to:
Post Comments (Atom)
Good One!
ReplyDeleteKeep it UP
It would be beneficial to see the actual change...not just the end result. I have no idea what was accomplished by this post.
ReplyDeletedoes this improve performance in anyways.. Please elaborate
ReplyDelete