Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
divyaps
Starting Member
4 Posts |
Posted - 2011-01-25 : 14:51:02
|
Hi, I have a table name A which has a primary key ID . This ID is a foreign key in 3 other tables. I want to check if this ID exists in any of the other three tables.I need to create a stored procedure which will take an ID as parameter and return 1 or 0 depending upon the value of ID present in any other table.So for ex if ID =3 and any of the n tables contains 3 the SP should return 1 else 0.What is the best way to achieve this?Please advice.I tried this sql, but it didnt workIF EXISTS ( SELECT * FROM A Left OUTER JOIN B ON A.Id = B.Id LEft outer JOIN C ON A.Id = C.Id Left Outer Join D ON A.Id = D.Id ) BEGIN SELECT 1 END ELSE BEGIN SELECT 0 END |
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2011-01-25 : 15:10:26
|
[code]CREATE PROCEDURE CheckID @ID int ASSET NOCOUNT ONSELECT CASE WHEN EXISTS(SELECT * FROM A WHERE ID=@ID) THEN 1 WHEN EXISTS(SELECT * FROM B WHERE ID=@ID) THEN 1 WHEN EXISTS(SELECT * FROM C WHERE ID=@ID) THEN 1ELSE 0 END AS FoundGO-- Example:EXEC CheckID @ID=12[/code] |
 |
|
|
|
|