简体   繁体   English

如何在多个表格中检查ID值

[英]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 ?? 我也想在MYTABLE2中检查此ID值。如何写IF条件? i want to check that a certain ID doesnt exist in any of the two tables. 我想检查两个表中的任何一个都不存在某个ID。

You could use an UNION ALL : 您可以使用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. 如果要检查ID是否存在于任何一个表中,请使用UNION ALL。 you could use JNK's answer. 您可以使用JNK的答案。

If you want to check that the ID exists in both tables then use INNER JOIN. 如果要检查两个表中是否都存在ID,请使用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 如果不存在(从table1的顶部1选择a.ID = b.ID的内部联接Table2 b,其中a.ID = @ID)开始结束

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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