0

我有一个游标,它获取数据并将其提取到@data_table 中。然后在 while 循环中,我想将该 @data_table 传递给另一个游标(作为表名)以运行更多处理。我不断收到声明 @data_table 错误。我该如何解决?

DECLARE @var_name varchar(50)
DECLARE @data_table varchar(50)
DECLARE @data_value varchar(50)

DECLARE curDiscreteVars CURSOR LOCAL

FOR SELECT DISTINCT v.var_name, v.data_table 
    FROM dbo.vars v
    GROUP BY v.var_name, v.data_table

-- Loop through cursor, translating variable values as needed, and generate counts for each val_code for a variable
OPEN curDiscreteVars
FETCH NEXT FROM curDiscreteVars 
    INTO @var_name, @data_table

WHILE @@FETCH_STATUS  = 0
BEGIN
    --loop through all possible data values

    DECLARE curValues CURSOR LOCAL

    FOR SELECT DISTINCT @var_name  
        FROM @data_table

    OPEN curValues
    FETCH NEXT FROM curValues 
        INTO @data_value

    WHILE @@FETCH_STATUS  = 0
    BEGIN
        print @var_name



        FETCH NEXT FROM curValues 
        INTO @data_value
    END

    CLOSE curValues
    DEALLOCATE curValues

    FETCH NEXT FROM curDiscreteVars 
    INTO @var_name, @data_table
END

CLOSE curDiscreteVars
DEALLOCATE curDiscreteVars
4

2 回答 2

1

就我而言,我不喜欢游标!对我来说,游标是邪恶的。给你锁和你不想要的。我总是做的是创建一个带有值的临时表(就像你通常插入光标一样)并用一个while循环遍历它

像这样 :

declare @currow int
      , @totrow int

create table #tmp_values (id int identity(1, 1), val int)

insert 
into   #tmp_values
select val
from   tableX

set @totrow = @@rowcount
set @currow = 1

while @totrow > 0 and @currow <= @totrow
begin
  select @val = val
  from   #tmp_values
  where id = @currow

  set @currow = @currow + 1
end

这样您就可以更好地控制事物,并且可以重复使用 tmp 表

于 2012-10-27T07:32:48.053 回答
0

我不确定我是否理解您在说什么,但变量不能用作表名。或者,实际上任何不是字段名称的东西。您需要使用动态 SQL。也就是说,将您的 SQL 字符串分配给一个变量,然后运行EXEC()命令。

例如:

 DECLARE @sqlcmd varchar(max)
 DECLARE @table_name sysname

 DECLARE cur_tables FOR
 SELECT name FROM sys.tables

 OPEN cur_tables
 FETCH NEXT FROM cur_tables INTO @table_name

 WHILE @@FETCH_STATUS = 0 BEGIN
 SET @sqlcmd = 'SELECT TOP 10 * FROM ' + QUOTENAME(@table_name)
 EXEC ( @sqlcmd )
 FETCH NEXT from cur_tables INTO @table_name
 END

 CLOSE cur_tables
 DEALLOCATE cur_tables

或者,如果您的意思是您需要一个位置来存储类似于表的数据,则为它创建一个临时表。

于 2012-10-27T03:21:08.640 回答