必须声明标量变量表

时间:2016-02-18 09:19:16

标签: sql sql-server tsql

我有以下SQL:

DECLARE @HospitalReport TABLE (Registrator VARCHAR (20))

INSERT INTO @HospitalReport (Registrator) 
VALUES("64")

SELECT 
    @HospitalReport.Registrator 
FROM 
    @HospitalReport

IF Registrator > 0
BEGIN
    SELECT 
        Database.dbo.Users.Firstname, Database.dbo.Users.Lastname 
    FROM 
        StradaAnv.dbo.Anvandare 
    WHERE 
        Id = Registrator

    IF Firstname != NULL AND Lastname != NULL
    BEGIN
        UPDATE @HospitalReport 
        SET Registrator = Firstname + ' ' + Lastname 
        WHERE Registrator = Registrator
    END 
END

SELECT * FROM @HospitalReport

当我运行此代码时,出现以下错误:

  

Msg 137,Level 16,State 1,Line 9
  必须声明标量变量" @ HospitalReport"

我看到的,我已经宣布@HospitalReport作为一张桌子?

1 个答案:

答案 0 :(得分:1)

不要将所有内容分解为程序步骤。告诉系统你想要什么,而不是如何做

DECLARE @HospitalReport TABLE (Registrator VARCHAR (20))

INSERT INTO @HospitalReport (Registrator) 
VALUES("64")

UPDATE H  
SET Registrator = Firstname + ' ' + Lastname
FROM
    @HospitalReport H
        INNER JOIN
    StradaAnv.dbo.Anvandare A
        ON
           H.Registrator = A.Registrator
WHERE A.Firstname IS NOT NULL AND
      A.Lastname IS NOT NULL

SELECT * FROM @HospitalReport

即。我不是先查询表格。然后查看特定列是否为空 1 。然后决定是否执行更新。我在单个查询中描述了整个操作,然后让优化器计算出如何最好地执行此任务。

1 如上所示,应该使用IS NULL运算符而不是!=来完成,因为NULL既不等于也不等于{{} 1}}