sql - SQL游标中表变量的范围

标签 sql cursor scope temp-tables table-variable

如果我在MS SQL 2008 R2中运行以下命令,则会得到意外的结果。

create table #DataTable (someID varchar(5))
insert into #DataTable 
values ('ID1'),('ID2'),('ID3'),('ID4'),('ID5')

declare @data varchar(8);

declare myCursor cursor for
select someID from #DataTable

open myCursor
FETCH NEXT FROM myCursor INTO
@data

WHILE(@@Fetch_Status >=0)
BEGIN 

    declare @tempTable table (someValue varchar(10))

    insert into @tempTable select @data + '_ASDF'
    select * from @tempTable    

FETCH NEXT FROM myCursor INTO
@data

END

close myCursor
deallocate myCursor

drop table #DataTable

上次迭代的结果:
someValue
ID1_ASDF
ID2_ASDF
ID3_ASDF
ID4_ASDF
ID5_ASDF

我只期望看到
someValue
ID5_ASDF

表变量@tempTable似乎在游标迭代之间保持作用域-但是如何在每次迭代中重新声明该变量呢?对我来说毫无意义。

我解决了
delete @tempTable

在每次迭代中-这也支持了我关于它仍在范围内的假设。

任何人都可以解释这种行为吗?

最佳答案

是的,它确实可以-范围不是由begin/end语句定义的,而是由存储过程或go的末尾定义的

The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.



http://msdn.microsoft.com/en-us/library/ms187953(v=sql.105).aspx

关于sql - SQL游标中表变量的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12348339/

相关文章:

ruby-on-rails - rails : Is it possible to check if a named scope is valid for a given active record?

python - 在超集中可视化 SQL Lab 查询的原始输出

php - Laravel - 选择列值第一次出现的行

python - 如何使用 SQLAlchemy 执行嵌套查询中存在的位置?

java - GetMetaData()->游标的状态不正确

iphone - UITextField > 强制光标停留在字段末尾

python ,SQLite3 : cursor returns duplicates when a commit intervenes

javascript - 函数内的jquery变量范围

sql - 复合数据库索引

ios - 其值在 block 内赋值的引用变量