从Select更新中的T-Sql语法错误

时间:2010-02-04 12:10:12

标签: sql sql-server tsql

我在T-Sql中有一个存储过程,其末尾有这段代码:

UPDATE @Results
SET Percentage = CASE B.Total
WHEN 0 THEN 0
ELSE (CAST(Number AS FLOAT)/B.Total)
END
FROM @TotalAnswersPerQuestion AS B
WHERE @Results.QuestionNumber=B.QuestionNumber

在这些说明之前,临时表@Results已在此存储过程中定义并正确使用,但我在最后一行收到错误说:

Msg 137,Level 15,State 2,Procedure Report,111行 必须声明标量变量“@Results”。

这是我的表格:

DECLARE @TotalAnswersPerQuestion Table
(QuestionNumber int,
Total int)

DECLARE @Results Table
(
    QuestionNumber int,
    QuestionTitle varchar(max),
    AnswerNumber int,
    AnswerLable varchar(max),
    ProfileGroupID int,
    [Name] varchar(255),
    Identifier varchar(20),
    Number int,
    Percentage float
)

怎么了?

3 个答案:

答案 0 :(得分:4)

UPDATE r
SET Percentage = 
    CASE B.Total
        WHEN 0 THEN 0
        ELSE (CAST(Number AS FLOAT)/B.Total)
    END
FROM @TotalAnswersPerQuestion AS B
INNER JOIN @Results r
ON r.QuestionNumber=B.QuestionNumber;

我对UPDATE FROM感到无耻!燃烧开始吧!

答案 1 :(得分:1)

别名:

UPDATE r
SET Percentage = CASE B.Total
WHEN 0 THEN 0
ELSE (CAST(Number AS FLOAT)/B.Total)
END
FROM   @Results r
JOIN   @TotalAnswersPerQuestion AS B
ON     r.QuestionNumber=B.QuestionNumber

答案 2 :(得分:0)

UPDATE r
SET Percentage = CASE B.Total
WHEN 0 THEN 0
ELSE (CAST(Number AS FLOAT)/B.Total)
END
FROM @Results r
,@TotalAnswersPerQuestion AS B
WHERE r.QuestionNumber=B.QuestionNumber