Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare table with a table variable in a Stored procedure in SQL Server 2005

How to compare a table against a table variable in a Stored Procedure? Normally to compare the two tables we used this query:

 SELECT * 
 FROM Table A 
 WHERE NOT EXISTS(SELECT * 
                  FROM Table B 
                  WHERE Table A.ID = Table B.ID)

But here, I have Table A and one table variable @Item like Table B.

In this scenario, how to compare Table A and @Item?

I am writing one stored procedure, in that stored procedure I want to compare the existing one table with the table variable which is generated from the front end and passed as a XML dataset to the Stored Procedure... In that, if all the rows in the table variable @Item presents in the existing table then it returns true else false...

Any suggestions please....

like image 428
thevan Avatar asked Dec 11 '25 09:12

thevan


2 Answers

I've always preferred the left-join syntax when excluding the results of one table:

select a.*
from [table] a
    left outer join @item b
        on a.ID = b.ID
where b.ID is null 

I suspect the query plan should come out the same though.

like image 60
Keith Avatar answered Dec 13 '25 10:12

Keith


If works just the same (altough using table aliases will make it easier)

SELECT * 
FROM Table A 
WHERE NOT EXISTS(
    SELECT * 
    FROM @Item sub 
    WHERE Table A.ID = sub.ID
)
like image 30
Jon Egerton Avatar answered Dec 13 '25 09:12

Jon Egerton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!