SQL Server存储过程将多行SELECT语句结果存储到单个变量中

时间:2018-10-02 00:44:49

标签: sql sql-server

我有一个带有SELECT语句的查询,结果将返回2行或更多行。如何将这些数据行存储到变量中?因为我需要变量来检查是否有任何行为空/空。我该如何实现?

到目前为止,我已经做到了:

BEGIN
    SELECT 
        @AINum = ISNULL(so.U_SI7_DPDocNum, 0), @soDocNum = so.DocNum
    FROM  
        DLN1 doline 
    INNER JOIN 
        ORDR so ON doline.BaseRef = so.DocNum
    WHERE 
        doline.DocEntry = @docEntry

    WHILE(@AINum IS NOT NULL)
    BEGIN
        IF(@AINum <= 0)
        BEGIN
            SELECT @errCode = 003;
            RETURN;
        END
    END
END

使用EXISTS更新查询

SELECT @errCode = 003
WHERE NOT EXISTS (SELECT so.U_SI7_DPDocNum
                  FROM DLN1 doline 
                  INNER JOIN ORDR so ON doline.BaseRef = so.DocNum
                  WHERE doline.DocEntry = @docEntry)
RETURN;

@AINum将必须存储SELECT语句结果中的多行数据。 @errCode是输出变量。

谢谢。

1 个答案:

答案 0 :(得分:1)

-- initialize to 0
SELECT  @errCode = 0;

-- assign value of 003 if it the DPDocNum is NULL or < 0
SELECT  @errCode = 003
FROM    DLN1 doline 
INNER JOIN ORDR so ON doline.BaseRef = so.DocNum
WHERE   doline.DocEntry = @docEntry
AND     (so.U_SI7_DPDocNum IS NULL OR so.U_SI7_DPDocNum <= 0)