SQL查询以从发起数据的位置获取表名

时间:2014-06-24 08:59:47

标签: sql

我在同一个DB的几个表上执行此查询,所有表都以相同的方式构建。 基本上,查询找到Table_xxx中列出的代码,这些代码不在表“组件”中。

SELECT DISTINCT a.Code, a.Description,  a.Quantity FROM Table_321 AS a
                        WHERE NOT EXISTS (SELECT * FROM Components where Components.Code = a.Code)
                        UNION ALL
SELECT DISTINCT a.Code, a.Description, a.Quantity FROM Table_333 AS a
                        WHERE NOT EXISTS (SELECT * FROM Components where Components.Code = a.Code)
                        UNION ALL
                        .............
                        .............
                        order by Code

如何获取最初包含“代码,描述和数量”的表名?

2 个答案:

答案 0 :(得分:1)

您可以在每个选择查询中添加额外的列tableName

SELECT DISTINCT a.Code, a.Description,  a.Quantity, 'Table_321' as tableName FROM Table_321 AS a
                        WHERE NOT EXISTS (SELECT * FROM Components where Components.Code = a.Code)
                        UNION ALL
SELECT DISTINCT a.Code, a.Description, a.Quantity, 'Table_333' as tableName FROM Table_333 AS a
                        WHERE NOT EXISTS (SELECT * FROM Components where Components.Code = a.Code)
                        UNION ALL
                        .............
                        .............
                        order by Code

答案 1 :(得分:0)

以下列格式提出您的查询:

SELECT DISTINCT a.Code, a.Description,  a.Quantity,'Table_321' AS tblName FROM Table_321 AS a 
WHERE a.Code NOT IN (SELECT Components.Code FROM Components)