将光标设置在表变量内的表上

时间:2015-12-01 14:54:34

标签: sql tsql stored-procedures

所有

尝试在表变量中的表值上设置游标,但它不起作用。任何人都可以评论我如何解决这个问题?

**下面的代码是从另一个存储过程调用的,它提供了tablename变量**的值

ALTER PROCEDURE [dbo].[usrSetLTDNormDist]
    -- Add the parameters for the stored procedure here
    @TableName Sysname,

---...

    DECLARE @SQLCommand1 NVARCHAR(MAX) = N'
    Set @RecCursor1 = Cursor For
        Select [Volume], [TRANSDATE] from @TableName'

    EXECUTE dbo.sp_executesql @sqlCommand1  

    -- Open  Cursor
    Open @RecCursor1
    Fetch Next From @RecCursor1
    Into @Volume, @TransDate

---...

2 个答案:

答案 0 :(得分:0)

PRINT @SQLCommand1DECLARE语句之间添加EXECUTE,以查看实际执行的内容。根据您的代码段,您将看到

Set @RecCursor1 = Cursor For
Select [Volume], [TRANSDATE] from @TableName

...也就是说,您在@TableName中设置的值不会自动添加到脚本中。这就是我写这些东西的方式:

DECLARE @SQLCommand1 NVARCHAR(MAX)

SET @SQLCommand1 = replace(N'
Set @RecCursor1 = Cursor For
Select [Volume], [TRANSDATE] from <@TableName>'
 ,'<@TableName>', @TableName)

PRINT @SQLCommand1

EXECUTE dbo.sp_executesql @sqlCommand1 

我使用&lt; &GT;使替换值突出的字符。

答案 1 :(得分:0)

此脚本演示了一般技术:

create table T (ID int not null)
go
insert into T(ID) values (99)
go
declare @TableName sysname
declare @ID int

set @TableName = 'T'

declare @SQL nvarchar(max) = N'declare boris cursor for select ID from ' + 
                               QUOTENAME(@TableName)

exec sp_executesql @SQL

open boris

fetch next from boris into @ID
while @@FETCH_STATUS = 0
begin
    print @ID

    fetch next from boris into @ID
end
close boris
deallocate boris

制作此输出:

(1 row(s) affected)
99

但是,我会提供我一贯的谨慎态度 - 如果你想以同样的方式对多个表进行操作,这通常是数据损坏的标志模型。通常应该有一个单个表,其中包含用于区分值的数据的附加列。