如何在sql表中查找特定名称

时间:2014-06-06 08:36:38

标签: sql-server-2008

我想检查名称是否存在于五个表格中,如果名称显示在五个表格中,则表示该人员有资格被拒绝,该怎么做。,任何想法,任何帮助。

1 个答案:

答案 0 :(得分:1)

DECLARE @Cnt int = 0;
DECLARE @t TABLE ( TableName VARCHAR(20));

SELECT TableName
INTO @t
FROM ( SELECT 'Table1' TableName
       FROM Table1
       WHERE Name = @Name

       UNION ALL

       SELECT 'Table2'
       FROM Table2
       WHERE Name = @Name

       UNION ALL

       SELECT 'Table3'
       FROM Table3
       WHERE Name = @Name

       UNION ALL

       SELECT 'Table4'
       FROM Table4
       WHERE Name = @Name

       UNION ALL

       SELECT 'Table5'
       FROM Table5
       WHERE Name = @Name
       ) a

SELECT a.TableName
FROM ( SELECT 'Table1'
       UNION ALL
       SELECT 'Table2'
       UNION ALL
       SELECT 'Table3'
       UNION ALL
       SELECT 'Table4'
       UNION ALL
       SELECT 'Table5') a
LEFT JOIN @t b
ON a.TableName = b.TableName
WHERE b.TableName IS NULL

SELECT @Cnt = COUNT(*)
FROM @t