合并表进行分段

时间:2014-10-21 12:10:31

标签: sql-server-2008 tsql ssis

这个实验性代码是否实现了将源表复制为临时数据库中的目标表的目标?:

IF OBJECT_ID('tempdb..#Source') IS NOT NULL
    DROP TABLE #Source
IF OBJECT_ID('tempdb..#Target') IS NOT NULL
    DROP TABLE #Target

CREATE TABLE #Source ( Id INT, Value CHAR(2) )
CREATE TABLE #Target ( Id INT, Value CHAR(2) )

INSERT  INTO #Source
        ( Id, Value ) values (1,'a'), (2,'b')    
INSERT  INTO #Target
        ( Id, Value )
        SELECT  1 ,
                'a1'

SELECT * FROM #Source
SELECT * FROM #Target

MERGE [#Target] AS Target
   USING [#Source] AS Source
     ON Target.Id = Source.Id
WHEN MATCHED AND
    (
         COALESCE(Target.Value, '') <> COALESCE(Source.Value, '')
    )
    THEN UPDATE SET
       Target.Value = Source.Value
WHEN NOT MATCHED
    THEN INSERT (
        Id
       ,Value
      ) VALUES (
        Source.Id
       ,Source.Value
      );

SELECT * FROM #Source
SELECT * FROM #Target 

非常欢迎任何改进/批评。

2 个答案:

答案 0 :(得分:1)

是的,这将实现您的目标。

您可以做的另一件事是在执行MERGE时执行增量/增量加载。仅从源表中获取上次运行后修改的记录。您可以使用UpdateDate列作为过滤器列,并在每次运行MERGE或ETL时将上次运行的日期存储在不同的表中。

答案 1 :(得分:-2)

Below is the complete script to merge the two tables 


CREATE TABLE StudentDetails
(
StudentID INTEGER PRIMARY KEY,
StudentName VARCHAR(15)
)
GO
INSERT INTO StudentDetails
VALUES(1,'SMITH')
INSERT INTO StudentDetails
VALUES(2,'ALLEN')
INSERT INTO StudentDetails
VALUES(3,'JONES')
INSERT INTO StudentDetails
VALUES(4,'MARTIN')
INSERT INTO StudentDetails
VALUES(5,'JAMES')
GO
CREATE TABLE StudentTotalMarks
(
StudentID INTEGER  ,
StudentMarks INTEGER
)
GO
INSERT INTO StudentTotalMarks
VALUES(1,230)
INSERT INTO StudentTotalMarks
VALUES(2,255)
INSERT INTO StudentTotalMarks
VALUES(3,200)
GO
-- Select from Table
SELECT *
FROM StudentDetails
GO
SELECT *
FROM StudentTotalMarks
GO
-- Merge Statement
MERGE StudentTotalMarks AS stm
USING (
SELECT StudentID,StudentName FROM StudentDetails
)
 AS sd
ON stm.StudentID = sd.StudentID
WHEN MATCHED AND stm.StudentMarks > 250 THEN DELETE
WHEN MATCHED THEN UPDATE SET stm.StudentMarks = stm.StudentMarks + 25
WHEN NOT MATCHED THEN
INSERT(StudentID,StudentMarks)
VALUES(sd.StudentID,25);
GO
-- Select from Table
SELECT *
FROM StudentDetails
GO
SELECT *
FROM StudentTotalMarks
GO
-- Clean up
DROP TABLE StudentDetails
GO
DROP TABLE StudentTotalMarks
GO