检查三个表中的条件和打印值

时间:2016-12-22 06:10:06

标签: sql sql-server sql-server-2008

我有表'tblPacks','tblBlisters','tblShippers'。现在我想要一个用户将发送的存储过程T_id,BatchNumber现在我必须检查这些表中是否存在T_id And BatchNumber。如果T_ID,BatchNumber存在于'tblPacks'中而不存在于'tblBlisters' and 'tblshippers'中它应该`打印T_ID,BatchNumber以及这两列出现的表的名称 例如: -

'tblPacks'表结构

 T_ID  BatchNumber PackId Status 
----   ----------  ------  -----
 1       101        ABC001  0

'tblBlisters'表结构

T_ID  BatchNumber BlisterId Status 
----   ----------  ------  -----
 1       101       PAC001  0

'tblShippers'表结构

T_ID  BatchNumber ShipperId Status 
----   ----------  ------  ----- 
  1       101        KBC001  0

例如,如果用户给出T_id,BatchNumber为1,101现在按条件我应该将T_ID打印为'1'BatchNumber为'101;并且应该打印'tblPacks,tblBlisters,tblShippers',因为T_id and BatchNumber存在于三个表中

1 个答案:

答案 0 :(得分:1)

以下查询将三个表联合在一起,然后聚合ID和批号,以生成存在ID和批号的表的CSV列表。

WITH cte AS (
    SELECT T_ID, BatchNumber, 'tblPacks' AS label
    FROM tblPacks
    UNION ALL
    SELECT T_ID, BatchNumber, 'tblBlisters'
    FROM tblBlisters
    UNION ALL
    SELECT T_ID, BatchNumber, 'tblShippers'
    FROM tblShippers
)

SELECT t1.T_ID,
       t1.BatchNumber,
       STUFF((SELECT N', ' + t2.label
              FROM cte AS t2
              WHERE t1.T_ID = t2.T_ID AND
                    t1.BatchNumber = t2.BatchNumber
              ORDER BY t2.label
              FOR XML PATH(N'')), 1, 2, N'') AS tables_present
FROM cte t1
WHERE t1.T_ID = 1 AND
      t1.BatchNumber = 101
GROUP BY t1.T_ID,
         t1.BatchNumber