0

I have a query with a SELECT statement that will return 2 or more rows as a result. How can I store these rows of data into a variable? Because I need the variable to check whether any of the rows is empty/null. How can I achieve this?

So far I've done this:

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

UPDATED query using 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;

The @AINum will have to store multiple rows of data from the SELECT statement result. @errCode is an output variable.

Thank you.

5
  • 1
    table var, or ..... a table! Commented Oct 2, 2018 at 0:45
  • @MitchWheat can the variable inside the table being used in while condition and null checking? Because it gaves me error when I want to use it in the while loop. Commented Oct 2, 2018 at 0:57
  • 1
    Tsql should not be procedural. You probably don't need a while loop. Look at Exists and 'Not Exists' Commented Oct 2, 2018 at 1:00
  • @granadaCoder I've updated the question with Exists clause, could you help me take a look on it? Thanks! Commented Oct 2, 2018 at 1:29
  • @Squirrel If the query return more than 2 rows and one of the U_SI7_DPDocNum is NULL, then pops up the errCode on the screen. Commented Oct 2, 2018 at 2:20

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.