临时表,go命令,

时间:2016-06-27 21:53:48

标签: sql-server tsql

我将以下代码写入SQL Server Management Studio

DECLARE @tab AS table(ProductID integer, StockCount integer)
INSERT INTO @tab
SELECT ProductID, InStock + OnOrder
FROM Inventory.Product;
GO
SELECT * FROM @tab;

执行代码时,会发生错误。我可以采取以下两项措施中的哪一项来防止错误发生?

1

Modify the INSERT statement to:
INSERT INTO @tab
SELECT ProductID, InStock
FROM Inventory.Product;

2

--Remove the GO command

3

--Use a temporary table named #tab instead of the @tab variable

4

--Add a second GO command after the final SELECT statement

就我个人而言,我认为1和2是正确的,但是由于轻微的残疾问题,我对自己的答案没有足够的信心100%正确,如果有人能给出任何肯定有帮助或解释为什么我可能的指示错。

编辑:当我开始查询时我犯了错误:

Msg 208, Level 16, State 1, Line 2
Invalid object name 'Inventory.Product'.
Msg 1087, Level 15, State 2, Line 6
Must declare the table variable "@tab".

3 个答案:

答案 0 :(得分:1)

您收到错误的原因是因为Variable的范围是声明它的事务。

当您将GO关键字作为批处理分隔符后立即声明变量时,该变量在该GO关键字后不可见。

无论如何,这些不是决定是使用表变量还是使用Temp表的因素。

看看这个问题What's the difference between a temp table and table variable in SQL Server,了解Temp表和表变量之间的差异,然后确定最适合您的问题。

答案 1 :(得分:0)

我会说2& 3是正确的。 Go不允许变量转移到第二个查询,但你可以通过使用临时表而不是变量来解决这个问题。

答案 2 :(得分:0)

2& 3确实是正确的。

  1. 删除go将其作为单个批处理,因此@tab var将是 可访问第二个SELECT stmnt
  2. 如果你需要将它分成两批,那么按照之前的建议 - 将它分成一个表。