SQL Server:语法错误进入存储过程

时间:2018-07-18 19:30:26

标签: sql-server tsql

我有一个简单的查询,例如:

SELECT
    1 AS [Result],
    'success' AS [ResultText]

IF (@TaskStatusName = 'COMPLETED')
    SELECT 
        5 AS [ToNotifiedResult],
        SELECT @TechniciansEmail = COALESCE(@TechniciansEmail + ';', '') + [Username]  
        FROM Employee  AS [E]
  INNER JOIN TaskNotification AS [TN] ON TN.EmpKey = E.EmpKey AND TaskId = '64BB7072-62A5-4C8E-A385-3B3DCB8BD1CA' AS [ToNotified]

问题在最后一次选择就说了

  

“选择”附近的语法不正确

“选择”字样标记为红色

我尝试将带括号的选择分组为:

 ,(SELECT @TechniciansEmail = COALESCE(@TechniciansEmail + ';', '') + [Username]  FROM Employee  AS [E]
  INNER JOIN TaskNotification AS [TN] ON TN.EmpKey = E.EmpKey AND TaskId = '64BB7072-62A5-4C8E-A385-3B3DCB8BD1CA' AS [ToNotified])

但是现在@ TechniciansEmail变量被标记为红色,我得到了

  

@TechniciansEmail附近的语法不正确。期待'('或SELECT

我真的不知道我在做什么错,有什么想法吗?

2 个答案:

答案 0 :(得分:0)

此行:

SELECT @TechniciansEmail = COALESCE(@TechniciansEmail + ';', '') + [Username] 

要么完全不合适,要么尝试创建一个子查询,在这种情况下,它需要放在括号中并具有自己的FROM子句。

实际上,根据问题的后半部分,您似乎应该将此行作为其自己的单独查询,因为它填充了一个变量:

SELECT  
    @TechniciansEmail = COALESCE(@TechniciansEmail + ';', '') + [Username]  
FROM 
    Employee  AS [E]
INNER JOIN 
    TaskNotification AS [TN] ON TN.EmpKey = E.EmpKey AND TaskId = '64BB7072-62A5-4C8E-A385-3B3DCB8BD1CA'

答案 1 :(得分:0)

如果在存储过程中,则必须以条件开始。 像这样 如果@sastro = value 开始 从参数=处选择* 结束 其他 开始

选择....... 结束