从WITH子句内部访问临时表

时间:2015-12-09 19:43:48

标签: sql-server

Msg 137, Level 16, State 1.
Must declare the scalar variable "@tempNums".
Msg 137, Level 16, State 1.
Must declare the scalar variable "@tempNames". (Line 25)

导致以下错误消息:

{{1}}

如何从WITH子句中访问临时表?

随机文字制作愚蠢的#34;主要代码"警告开始。

1 个答案:

答案 0 :(得分:0)

这些不是临时表,它们是表变量,必须稍微区别对待。您需要在查询中使用别名,而不是尝试再次使用表变量的名称。无论如何,你真的应该养成使用别名的习惯。

DECLARE @tempNums TABLE(
    id INT PRIMARY KEY IDENTITY(1,1),
    val INT
);

DECLARE @tempNames TABLE(
    id INT PRIMARY KEY IDENTITY(1,1),
    name VARCHAR(10)
);

DECLARE @combined TABLE(
    val INT,
    name VARCHAR(10)
);

INSERT INTO @tempNums(val) VALUES (1),(2),(3);
INSERT INTO @tempNames(name) VALUES ('one'),('two'),('three');

WITH cte AS (
    SELECT 
        tNum.val AS 'val',
        tName.name AS 'name'
    FROM @tempNums tNum
        INNER JOIN @tempNames tName
            ON tNum.val = tName.id
)
MERGE INTO @combined
    USING cte ON 1 = 0
WHEN NOT MATCHED THEN
    INSERT (val,name)
    VALUES(cte.val, cte.name);

SELECT * from @combined;