How do I fetch multiple columns for use in a cursor loop?

后端 未结 1 410
孤独总比滥情好
孤独总比滥情好 2020-12-22 17:43

When I try to run the following SQL snippet inside a cursor loop,

set @cmd = N\'exec sp_rename \' + @test + N\',\' +
           RIGHT(@test,LEN(@test)-3) +          


        
相关标签:
1条回答
  • 2020-12-22 18:04

    Here is slightly modified version. Changes are noted as code commentary.

    BEGIN TRANSACTION
    
    declare @cnt int
    declare @test nvarchar(128)
    -- variable to hold table name
    declare @tableName nvarchar(255)
    declare @cmd nvarchar(500) 
    -- local means the cursor name is private to this code
    -- fast_forward enables some speed optimizations
    declare Tests cursor local fast_forward for
     SELECT COLUMN_NAME, TABLE_NAME
       FROM INFORMATION_SCHEMA.COLUMNS 
      WHERE COLUMN_NAME LIKE 'pct%' 
        AND TABLE_NAME LIKE 'TestData%'
    
    open Tests
    -- Instead of fetching twice, I rather set up no-exit loop
    while 1 = 1
    BEGIN
      -- And then fetch
      fetch next from Tests into @test, @tableName
      -- And then, if no row is fetched, exit the loop
      if @@fetch_status <> 0
      begin
         break
      end
      -- Quotename is needed if you ever use special characters
      -- in table/column names. Spaces, reserved words etc.
      -- Other changes add apostrophes at right places.
      set @cmd = N'exec sp_rename ''' 
               + quotename(@tableName) 
               + '.' 
               + quotename(@test) 
               + N''',''' 
               + RIGHT(@test,LEN(@test)-3) 
               + '_Pct''' 
               + N', ''column''' 
    
      print @cmd
    
      EXEC sp_executeSQL @cmd
    END
    
    close Tests 
    deallocate Tests
    
    ROLLBACK TRANSACTION
    --COMMIT TRANSACTION
    
    0 讨论(0)
提交回复
热议问题