使用包含SELECT语句的IF / ELSE设置变量

时间:2018-11-07 14:11:06

标签: sql sql-server tsql

尝试将变量设置为字符串时,我在语法错误中运行。该字符串在IF/ELSE语句中构造,该语句将基于字段为null的形式提供消息的变体。我在SELECT行之后的set @errorMsg上收到语法错误。然后将在另一个查询中调用该变量。此时,我不确定查询是否有问题,或者我是否看错了。

declare @errorMsg nvarchar(MAX)
declare @combinedString VARCHAR(MAX)

IF EXISTS (select y from db.b)
    BEGIN
    set @errorMsg =
        SELECT @combinedString = COALESCE(@combinedString + ', ', '') + x_y
        from (select CONCAT(cg.x, '-', f.y) AS x_y
        from db.a cg
        LEFT JOIN db.b f
        ON cg.x = f.y) AS w
        SELECT 'The x listed in the database are (x - y if applicable): ' + @combinedString as StringValue
    END
ELSE
    BEGIN
    set @errorMsg =
        SELECT @combinedString = COALESCE(@combinedString + ', ', '') + x_y
        from (select cg.x AS x_y
        from db.a) AS w
        SELECT 'The x listed in the database are (x - y if applicable): ' + @combinedString as StringValue
    END

1 个答案:

答案 0 :(得分:1)

在查询时,“ SET @errorMsg”可能位于错误的位置。

<persName  nymRef="#Guilhem_Canast-Brus_MSP-AU" role="own">Willelmi<lb break="y" n="20"/>de Canast Brus</persName>