TSQL:检查将数据插入表中

时间:2016-02-26 16:53:25

标签: sql sql-server tsql primary-key composite-primary-key

假设我有这张表:

CREATE TABLE [dbo].[finaleTable](
    [VENDId] [bigint] NOT NULL,
    [companyName] [nvarchar](4) NULL,
    ----Others field

    CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED   ([VENDId])
) ON [PRIMARY]
GO

这个查询:

INSERT INTO dbo.finaleTable
SELECT *
FROM Tmp1

在将数据插入表之前,我必须检查这两个字段的完整性约束。如果值存在,则移至从表TMP1获取的下一行数据。如果它们不存在则插入该行。

你能否建议我如何才能做到这一点?

2 个答案:

答案 0 :(得分:1)

我认为你需要MERGE这样:

MERGE dbo.finaleTable AS target
USING (SELECT VENDId, companyName... FROM Tmp1) AS source
ON target.VENDId = source.VENDId AND ISNULL(target.companyName,'') = ISNULL(source.companyName,'')
WHEN NOT MATCHED THEN
    INSERT (VENDId, companyName...)
    VALUES (source.VENDId, source.companyName...)

如果需要检查companyName,则必须为NOT NULL

答案 1 :(得分:1)

你也可以使用存在的地方 -

insert into finaleTable
select * from table1 as a
where not exists(select 1 from finaleTable as b where b.VENDId = a.VENDId)