【发布时间】:2017-05-22 18:58:57
【问题描述】:
我定义了这张表:
CREATE TABLE #stagingtable
(
id int identity(1,1),
typeflag int default 0,
resourcetype varchar(25),
resource varchar(40),
est int,
planned int,
actual int
)
And then I am looking for places where the resourcetype is not the same as the resourcetype in the previous row, so I wrote the following UPDATE:
UPDATE #stagingtable
SET typeflag = 1
WHERE id = (
SELECT min(id)
FROM #stagingtable
)
OR resourcetype <> (
SELECT resourcetype
FROM #stagingtable rt2
WHERE rt2.id = (
SELECT MAX(id)
FROM #stagingtable rt3
WHERE rt3.id < #stagingtable.id
)
)
这非常有效。但是,我所处的环境不允许我使用临时表(RDL!)。所以我把我的表改成了表值变量:
DECLARE @stagingtable TABLE
(
id int identity(1,1),
typeflag int default 0,
resourcetype varchar(25),
resource varchar(40),
est int,
planned int,
actual int
)
But the following code doesn't work.
UPDATE @stagingtable
SET typeflag = 1
WHERE id = (
SELECT min(id)
FROM @stagingtable
)
OR resourcetype <> (
SELECT resourcetype
FROM @stagingtable rt2
WHERE rt2.id = (
SELECT MAX(id)
FROM @stagingtable rt3
WHERE rt3.id < @stagingtable.id
)
)
我收到消息:
Msg 137, Level 16, State 1, Line 431 必须声明标量变量 “@stagingtable”。
有没有办法更改更新语句以使其正常工作?
【问题讨论】:
-
@variables 是批次的本地变量。我假设您在某个地方有一个 GO 命令,或者正在其他可访问的地方运行它。您可以尝试@@variable,但如果您试图随时保留此变量,则不可行。为什么不直接使用#temp?
标签: sql sql-server tsql correlated-subquery rdl