在sql server

时间:2017-04-08 09:59:05

标签: sql sql-server

考虑下表。

Table 1:
ID Name Address DateOfBirth DateOfJoin CurrentProject


Table 2:
ID Name DateOfJoin CurrentProject

如何编写sql server db脚本以将表2中的数据复制到表1,以便表2的值在合并时应覆盖表1的值,除非表2的值为null。 如果表2的值为null,则表1的值优先。

在上表中的示例中,DataofJoinCurrentProject的值应成为表1中特定ID的值。当表2中的DateOfJoin和CurrentProject值为空时,表1的值将保持不变。此外,在运行脚本后,应将表2中但表1中未出现的所有ID复制到表1中。

1 个答案:

答案 0 :(得分:1)

    BEGIN

    CREATE TABLE #Table1(
    ID INT, 
    Name VARCHAR(50), 
    Address VARCHAR(50),
    DateOfBirth DATE,
    DateOfJoin DATE,
    CurrentProject VARCHAR(50)
    )

    CREATE TABLE #Table2(
    ID INT, 
    Name VARCHAR(50), 
    DateOfBirth DATE,
    DateOfJoin DATE,
    CurrentProject VARCHAR(50)
    );

    INSERT INTO #Table1 VALUES
    (1,'NAME 1','ADDRESS 1','01/01/1990','01/01/2017','PROJECT 1'),
    (2,'NAME 1','ADDRESS 2','01/01/1991','01/01/2017','PROJECT 2'),
    (3,'NAME 1','ADDRESS 3','01/01/1992','01/01/2017','PROJECT 3'),
    (4,'NAME 1','ADDRESS 4','01/01/1993','01/01/2017','PROJECT 4');


    INSERT INTO #Table2 VALUES
    (1,'NAME 1','01/01/1990','01/01/1988',NULL),
    (3,'NAME 3','01/01/1991',NULL,'PROJECT 33'),
    (5,'NAME 5','01/01/1986','01/01/2017','PROJECT 5'),
    (6,'NAME 6','01/01/1985','01/01/2017','PROJECT 6');


    SELECT * FROM #Table1;
    SELECT * FROM #Table2;

    --  Insert records which exists in Table but not in table 1
    INSERT INTO #Table1(ID,Name,DateOfBirth,DateOfJoin,CurrentProject) SELECT * FROM #Table2 WHERE ID not in (SELECT ID FROM #table1) 

    -- Update matching id records from table 1 with table 2
    UPDATE #Table1 SET 
    Name = CASE WHEN T2.Name='' or T2.Name IS NULL THEN #Table1.Name ELSE T2.Name END, 
    DateOfBirth = CASE WHEN T2.DateOfBirth='' or T2.DateOfBirth IS NULL THEN #Table1.DateOfBirth ELSE T2.DateOfBirth END, 
    DateOfJoin = CASE WHEN T2.DateOfJoin='' or T2.DateOfJoin IS NULL THEN #Table1.DateOfJoin ELSE T2.DateOfJoin END, 
    CurrentProject = CASE WHEN T2.CurrentProject='' or T2.CurrentProject IS NULL THEN #Table1.CurrentProject ELSE T2.CurrentProject END
    FROM #Table2 T2 WHERE #Table1.ID= T2.ID 

    select * from #Table1

    drop table #Table1;
    drop table #Table2;


    END