子查询返回的值超过1。我究竟做错了什么?

时间:2019-01-22 15:09:30

标签: sql-server tsql

我有一个存储过程,无法执行,因为出现以下错误:

  

子查询返回了多个值。当   子查询遵循=,!=,<,<=,>,> =,或当子查询用作   表达式。”

这是发生问题的存储过程的一部分。我在CURSOR中使用这段代码(只要我理解正确)就可以逐条记录。考虑到这一点。我没看到问题。

SELECT @Public_amount = (SELECT
    CASE 
    WHEN cl.[Tram_periodicity] = '1' THEN pca.[5day] -- of 6 dagen, who knows?
    WHEN cl.[Tram_periodicity] = '2' THEN pca.Monthly
        -- According to Marina, trimestriële is never used. This is code '3'
    WHEN cl.[Tram_periodicity] = '4' THEN pca.Yearly
    WHEN cl.[Tram_periodicity] = '5' THEN pca.Railflex
    ELSE NULL
    END
    FROM [TC].[TC_Control_List] AS cl
    LEFT JOIN [TC].[PC_amount] AS pca
    ON cl.CPARC = pca.PC
    WHERE (CAST(@TRAM_DISTANCE AS NUMERIC)>=pca.[FROM] AND CAST(@TRAM_DISTANCE AS NUMERIC)<=pca.till)
    AND pca.Type = 'Public' AND pca.PC = '20000')

1 个答案:

答案 0 :(得分:0)

错误消息清楚地表明,您的subquery返回了多个记录,您需要top (1)子句或使用表变量来将所有行存储在表中:

SELECT TOP (1) @Public_amount = CASE WHEN cl.[Tram_periodicity] = '1' THEN pca.[5day] -- of 6 dagen, who knows?
                                     WHEN cl.[Tram_periodicity] = '2' THEN pca.Monthly -- According to Marina, trimestriële is never used. This is code '3'
                                     WHEN cl.[Tram_periodicity] = '4' THEN pca.Yearly
                                     WHEN cl.[Tram_periodicity] = '5' THEN pca.Railflex
                                END
 . . . 

但是,这可能无法解决您的实际问题,但是可以解决编译错误。