cursors, temp table

Upload: mrlogan123

Post on 04-Jun-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 Cursors, Temp Table

    1/3

    Method 1: Temp table with identity column

    In the first approach, we will use a temp table with an identity column added toallow for row-by-row selection. If you're performing an INSERT/UPDATE/DELETE, be sure to use the explicit transactions. This vastly reduces the load on your log file by committing per loop, and it prevents huge rollbacks in the case of failure.

    set nocount ondeclare @i int --iteratordeclare @iRwCnt int --rowcountdeclare @sValue varchar(100)set @i = 1 --initializecreate table #tbl(ID int identity(1,1), Value varchar(100))insert into #tbl(Value)select namefrom master..sysdatabases (nolock)set @iRwCnt = @@ROWCOUNT --SCOPE_IDENTITY() would also workcreate clustered index idx_tmp on #tbl(ID) WITH FILLFACTOR = 100

    /*

    Always do this after the insert, since it's faster to add the index in bulk thanto update the index as you write into the temp table. Since you know the data in this column, you can set the fill factor to 100% to get the best read times.

    */while @i

  • 8/13/2019 Cursors, Temp Table

    2/3

    insert into #tbl(Value)select namefrom master..sysdatabases (nolock)set @iRwCnt = @@ROWCOUNT --SCOPE_IDENTITY() would also workcreate clustered index idx_tmp on #tbl(Value) WITH FILLFACTOR = 100/*

    Always do this after the insert, since it's faster to add the index in bulk thanto update the index as you write into the temp table. Since you know the data in this column, you can set the fill factor to 100% to get the best read times.

    */while @iRwCnt > 0beginselect top 1 @sValue = Value from #tblset @iRwCnt = @@ROWCOUNT --ensure that we still have dataif @iRwCnt > 0begin--begin tran

    print 'My Value is ' + @sValue --replace with your operations on this value--commit trandelete from #tbl where value = @sValue --remove processed recordendenddrop table #tbl

    Method 3: Selecting a comma-delimited list of items

    When most developers/DBAs are asked to come up with a list of comma-delimited values from a table, they typically use a cursor or temp table (as above) to loop

    through the records. However, if you do not need to use a GROUP BY or an ORDER BY, then you can use the method below that operates in batch to handle the task.This cannot be used with GROUP BY DISTINCT, or ORDER BY, because of how SQL Server handles those operations.

    Basically, this takes a given variable, and for every row in the table it adds the current value to the variable along with a comma.

    declare @vrs varchar(4000)declare @sTbl sysnameset @sTbl = 'TableName'set @vrs = ''select @vrs = @vrs + ', ' + name from syscolumns where id = (select st.id from

    sysobjects as st where name = @sTbl) order by colorderset @vrs = right(@vrs, len(@vrs)-2)print @vrs

    DECLARE @StudentID char(11); DECLARE crs CURSOR READ_ONLYFORSELECT student_idFROM studentsOPEN crsFETCH NEXT FROM crsINTO @StudentIDWHILE @@FETCH_STATUS = 0BEGIN PRINT @StudentID FETCH NEXT FROM crs INTO @StudentIDENDCLOSE crsDEALLOCATEcrsThe definitions for the terminology are :-

    DECLARE CURSOR

  • 8/13/2019 Cursors, Temp Table

    3/3

    this statement defines the SELECT statement that forms the basis of the cursor.

    You can do just about anything here that you can do in a SELECT statement.OPEN statement executes the SELECT statement and populates the result set.

    FETCHstatement returns a row from the result set into the variable.You can select multiple columns and return them into multiple variables.The variable @@FETCH_STATUS is used to determine if there are any more rows.

    It will contain 0 as long as there are more rows.We use a WHILE loop to move through each row of the result set.

    READ_ONLY clause is important in the code above. That improves the performanceof the cursor.

    CLOSE statement releases the row set

    DEALLOCATE statement releases the resources associated with a cursor.