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??
You could use not exists
:
if (not exists (select 1 from #tempdataatable))
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With