check if id exists in multiple tables

后端 未结 2 1247
野的像风
野的像风 2021-01-26 07:02

I am using SQL Server 2012.

I have 5 tables (lets call them A, B, C, D & E). Each table contains a column called m_id, which contains id\'s that are nvarchar(10).

2条回答
  •  太阳男子
    2021-01-26 07:51

    You can use this:

    SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END as returnCode
    FROM (
        SELECT m_id, N'A' as tableName FROM A WHERE m_id = 'some_id'
        UNION ALL
        SELECT m_id, N'B' as tableName FROM B WHERE m_id = 'some_id'
        UNION ALL
        SELECT m_id, N'C' as tableName FROM C WHERE m_id = 'some_id'
        UNION ALL
        SELECT m_id, N'D' as tableName FROM D WHERE m_id = 'some_id'
        UNION ALL
        SELECT m_id, N'E' as tableName FROM E WHERE m_id = 'some_id'
    ) data
    

提交回复
热议问题