如何在游标中分配值?

时间:2015-02-02 03:48:20

标签: sql sql-server sql-server-2008

PeriodTable中有三个时段JAN,FEB,MARCH

现在我想要三个查询:

   SELECT JAN FROM MainTable

   SELECT FEB FROM MAinTable

   SELECT MARCH FROM MAinTable

我已经声明了一个游标,我想在查询中分配@period值吗?

DECLARE @period varchar(max),
        @temp varchar(max)
DECLARE @dquery varchar(max)
SET @period=''
    DECLARE Period_Cursor CURSOR For SELECT DISTINCT period FROM dbo.PeriodTable
      OPEN Period_Cursor
      FETCH NEXT FROM Period_Cursor INTO @temp
     WHILE @@FETCH_STATUS=0
BEGIN

       SET @period=@period+'['+@temp+']'
       SELECT '''+@period+''' FROM MainTable
       FETCH NEXT FROM Period_Cursor INTO @temp
END
    CLOSE Period_Cursor
    DEALLOCATE Period_Cursor
    PRINT (@period)

但是没有正常工作。

1 个答案:

答案 0 :(得分:1)

你必须为此使用动态sql。如果要动态选择列,则需要将整个SELECT语句包装在动态sql中,并在single-qoutes'+ @period +'之类的+运算符中使用use table name,最后执行它。

Declare @period varchar(max),
      @temp varchar(max)
      DECLARE @dquery varchar(Max)
      set @period=''
       declare Period_Cursor cursor for select distinct period from        dbo.PeriodTable
      open Period_Cursor
      fetch next from Period_Cursor into @temp
     while @@FETCH_STATUS=0
     begin

       set @period=@period+'['+@temp+']'

      set @dquery = 'select '+@period+' from MainTable'
      EXEC SP_EXECUTESQL @dquery 

       fetch next from Period_Cursor into @temp
      end
    close Period_Cursor
    Deallocate Period_Cursor
    print(@period)