Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IF statement to check if temporary table has rows in a stored procedure

How can I use an IF statement in my stored procedure to check if my temporary table has rows?

I want to check if #TempDataTable has rows then I would do either of the two statements, insert or update depending on the output.

I did the following:

BEGIN
    SELECT * 
    INTO #TempDataTable 
    FROM
        (SELECT * 
         FROM BranchNameTable BT 
         LEFT JOIN BranchLocationActivate BLA ON BT.loc_id = BLA.loc_id 
         WHERE BT.Branchloc = 1;) as Q

    if(//TempDataTable has 0 rows)

       INSERT INTO BranchLocationActivate 
       VALUES(//my values)

    ELSE

       UPDATE BranchLocationActivate 
       SET //My values where //my values
END

How do I put it after my select statement in my procedure??

like image 490
marchemike Avatar asked Aug 06 '14 03:08

marchemike


3 Answers

You could use not exists:

if (not exists (select 1 from #tempdataatable))
like image 101
Gordon Linoff Avatar answered Oct 22 '22 13:10

Gordon Linoff


Assuming that there are not any SQL statements between SELECT * INTO #TempDataTable and if(//TempDataTable has 0 rows) then you don't even need the temp table in the first place. Instead you should simplify the test to be just:

IF (NOT EXISTS(
                SELECT *
                FROM BranchNameTable BT
                LEFT JOIN BranchLocationActivate BLA
                       ON BT.loc_id = BLA.loc_id
                WHERE BT.Branchloc = 1
              )
   )
BEGIN
   INSERT INTO BranchLocationActivate VALUES(//my values)
END;
ELSE
BEGIN
   UPDATE BranchLocationActivate SET //My values where //my values
END;

If there are statements between those parts that make use of the temp table, then you can simplify by using the information SQL Server already gives you after the DML statement via the @@ROWCOUNT variable:

DECLARE @RowsInserted INT;

SELECT *
INTO #TempDataTable
FROM BranchNameTable BT
LEFT JOIN BranchLocationActivate BLA
       ON BT.loc_id = BLA.loc_id
WHERE BT.Branchloc = 1;

SET @RowsInserted = @@ROWCOUNT;

-- other statements

IF (@RowsInserted = 0)
BEGIN
   INSERT INTO BranchLocationActivate VALUES(//my values)
END;
ELSE
BEGIN
   UPDATE BranchLocationActivate SET //My values where //my values
END;
like image 21
Solomon Rutzky Avatar answered Oct 22 '22 13:10

Solomon Rutzky


You can either proceed with the solution mentioned by Gordon Linoff above, or if the the number of rows might help / a simpler way would be the below;

DECLARE @Count AS INT
Select @Count = count (*) from #tempdataatable

If @Count = 0 
BEGIN
    ...
ELSE
    ...
END
like image 22
Nadeem_MK Avatar answered Oct 22 '22 12:10

Nadeem_MK