如何删除 SQL-Server 中的表变量?我应该这样做吗?
我在脚本中有一个表变量(不是存储过程)。有两个问题:
- 如何删除表变量?删除表 @varName 给出“不正确的 snytax”错误。
- 我应该总是这样做吗?我听说这是一个很好的做法。像这样的小脚本真的有必要吗?
这是我的代码:
Declare @projectList table(
name varchar(40) NOT NULL);
Insert Into @projectList
Values ('BCR-00021')
Select *
From @projectList
Drop Table @projectList -- does not work
I have a table variable in a script (not a stored procedure). Two questions:
- How do I drop the table variable? Drop Table @varName gives an "Incorrect snytax" error.
- Should I always do this? I hear it's a good practice. Is it ever really necessary for small scripts like this?
Here's my code:
Declare @projectList table(
name varchar(40) NOT NULL);
Insert Into @projectList
Values ('BCR-00021')
Select *
From @projectList
Drop Table @projectList -- does not work
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
表变量自动成为本地变量并自动删除——您不必担心这一点。
Table variables are automatically local and automatically dropped -- you don't have to worry about it.
如果其他人遇到这个...并且您确实需要像循环中一样删除它,您可以从表变量中删除所有内容:
if somebody else comes across this... and you really need to drop it like while in a loop, you can just delete all from the table variable:
表变量就像 int 或 varchar 变量。
你不需要丢掉它们。它们与 int 或 varchar 变量具有相同的范围规则
Table variables are just like int or varchar variables.
You don't need to drop them. They have the same scope rules as int or varchar variables
但你们都忘记提及,如果在循环中使用变量表,则需要先清空(删除@table),然后再在循环中再次加载数据。
But you all forgot to mention, that if a variable table is used within a loop it will need emptying (delete @table) prior to loading with data again within a loop.
就像 TempTables 一样,TempDB 中也创建了一个本地表变量。表变量的作用域是声明它的批处理、存储过程和语句块。它们可以作为参数在过程之间传递。当您关闭创建它们的会话时,它们会自动删除。
Just Like TempTables, a local table variable is also created in TempDB. The scope of table variable is the batch, stored procedure and statement block in which it is declared. They can be passed as parameters between procedures. They are automatically dropped when you close that session on which you create them.
临时表变量保存到temp.db,范围仅限于当前执行。因此,与删除临时表(例如删除表#tempTable)不同,我们不必显式删除临时表变量@tempTableVariable。它由 sql server 自动处理。
Temp table variable is saved to the temp.db and the scope is limited to the current execution. Hence, unlike dropping a Temp tables e.g drop table #tempTable, we don't have to explicitly drop Temp table variable @tempTableVariable. It is automatically taken care by the sql server.
事实上,您不需要删除
@local_variable
。但如果你使用#local_table,就可以做到,例如可以方便地多次重新执行查询。
您还可以将 SELECT 语句放入 TRANSACTION 中,以便能够在没有显式 DROP 的情况下重新执行:
Indeed, you don't need to drop a
@local_variable
.But if you use
#local_table
, it can be done, e.g. it's convenient to be able to re-execute a query several times.You can also put your SELECT statement in a TRANSACTION to be able to re-execute without an explicit DROP:
这是一个
在 SQL Server 2014 上运行良好的 解决方案
克里斯托夫
Here is a solution
Works fine on SQL Server 2014
Christophe