如何在多个表中检查记录的存在

时间:2016-11-26 01:13:33

标签: sql sql-server tsql

在将记录插入表之前,如何检查三个不同表中是否存在bomItem字段值。我想检查是否

    1. `bomitem` of `BOMHEAD` Table with `itemId` of `Table A`
         or
    2. `bomitem` of `BOMHEAD` Table with `itemId` of `Table B`
         or 
    3. `bomitem` of `BOMHEAD` Table with `itemId` of `Table C`

相等

如果存在于三个表中的任何一个表中,则可以在BOMHEAD表中创建记录。上述三个表中唯一的共同字段是itemId字段,它们包含广泛不同的属性。

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[BOMHEAD](
    [bomItem] [int] NOT NULL,
    [bomRev] [nvarchar](6) NOT NULL,

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

示例数据

Table A
100199
100200
100201

Table B.
200199
200200
200201
200202

table C
400199
400200
400201

现在我想添加我想录制到BOMHEAD

INSERT INTO BOMHEAD (bomItem) VALUES (400199); //OK since exist in Table C
INSERT INTO BOMHEAD (bomItem) VALUES (200202); //OK since exist in Table B
INSERT INTO BOMHEAD (bomItem) VALUES (500202); //NO because doesnt exist in either A or B or C tables

1 个答案:

答案 0 :(得分:1)

使用EXISTS检查表中是否存在记录。这是一种方式

INSERT INTO BOMHEAD(bomItem)
SELECT bomItem
FROM   (VALUES (400199),
               (200202),
               (200202))tc(bomItem) 
WHERE  EXISTS (SELECT 1 FROM TableA A WHERE tc.bomItem = A.itemId)
        OR EXISTS (SELECT 1 FROM TableB B WHERE tc.bomItem = B.itemId)
        OR EXISTS (SELECT 1 FROM TableC C WHERE tc.bomItem = C.itemId) 

另一种方法(可能没有上述查询那么高效。使用您的实际数据运行它来检查性能)。

INSERT INTO BOMHEAD
            (bomItem)
SELECT bomItem
FROM   (VALUES (400199),
               (200202),
               (200202))tc(bomItem)
WHERE  EXISTS (SELECT 1
               FROM   (SELECT itemId FROM TableA A
                       UNION ALL
                       SELECT itemId FROM TableB B
                       UNION ALL
                       SELECT itemId FROM TableC C) a
               WHERE  a.itemId = tc.bomItem)