如何在SQL Server中合并两个表?

时间:2016-05-25 12:51:39

标签: sql-server

我有两个包含这样的模式的表:

CREATE TABLE [dbo].[WordsA] (
    [WordId] INT            IDENTITY (1, 1) NOT NULL,
    [Word]   NVARCHAR (MAX) NOT NULL
    [FromWordA] BIT NULL,
    [FromWordB] BIT NULL
);

CREATE TABLE [dbo].[WordsB] (
    [WordId] INT            IDENTITY (1, 1) NOT NULL,
    [Word]   NVARCHAR (MAX) NOT NULL
);

如何获取表格WordsB的内容并逐行插入WordsA:

如果WordsA中不存在Word

Insert into WordsA and set FromWordB = 1

如果WordsA中存在Word

Update WordsA setting FromWordB = 1

2 个答案:

答案 0 :(得分:1)

尝试一下(未经测试):

MERGE WordsA A
    USING       WordsB      B
    ON          A.WordId = B.WordID
    WHEN NOT MATCHED BY SOURCE THEN
                INSERT (Word, FromWordB)
                VALUES (B.Word, 1)
    WHEN MATCHED THEN
                UPDATE SET FromWordB = 1
;

答案 1 :(得分:1)

你需要MERGE:

MERGE [dbo].[WordsA] as target
USING [dbo].[WordsB] as source
ON target.[Word] = source.[Word] 
WHEN MATCHED THEN 
    UPDATE SET [FromWordB] = 1
WHEN NOT MATCHED THEN 
    INSERT ([Word],[FromWordA],[FromWordb]) 
    VALUES (source.[Word],0,1);