简体   繁体   中英

How do I check for an ID value in more than one table

if not exists(SELECT 1 FROM MYTABLE1 WHERE ID=@ID)

BEGIN

END

I want to check for this ID value in MYTABLE2 as well..how should I write the IF condition ?? i want to check that a certain ID doesnt exist in any of the two tables.

You could use an UNION ALL :

IF NOT EXISTS (SELECT 1 FROM
                        (SELECT ID FROM MyTable1
                         UNION ALL
                         SELECT ID FROM MyTable2) Table
               WHERE ID = @ID)
BEGIN
...
END

You could do the following:

if (not exists(SELECT 1 FROM MYTABLE1 WHERE ID=@ID)) 
     AND (not exists(SELECT 1 FROM MYTABLE2 WHERE ID=@ID))

BEGIN

END
SELECT
    blah.ID
FROM
    MYTABLE1 as blah
WHERE
    blah.ID IN (some range of ints)

If you get no results then you know it does not exist

Depends on what you want -

If you want to check that the ID exists in either ONE of the tables then use UNION ALL. you could use JNK's answer.

If you want to check that the ID exists in both tables then use INNER JOIN.

If not exists (select top 1 from table1 a inner join Table2 b on a.ID = b.ID where a.ID = @ID) BEGIN END

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM