看起來你正在試圖用char或varchar類型的數據更新日期或日期時間類型列,這些數據不可轉換爲日期或日期時間類型。 'a'不能轉換爲日期或日期時間。查看下面的第一個和第二個合併。如果您沒有提及何時匹配或何時不匹配源或目標,默認情況下它會考慮Target。
--DROP TABLE #A;
--DROP TABLE #B;
CREATE TABLE #A
(
ipval VARCHAR(50)
, domain CHAR(5)
, dateStart DATE
, dateUpdate DATE
, dateFinish DATE
, link VARCHAR(50)
);
CREATE TABLE #B
(
ipval VARCHAR(50)
, domain CHAR(5)
, dateStart DATE
, dateUpdate DATE
, dateFinish DATE
, link VARCHAR(50)
);
INSERT INTO #B
(ipval, domain, dateStart, dateUpdate, dateFinish, link)
VALUES ('42.130.239.56' -- ipval - varchar(50)
, '.com' -- domain - char(5)
, GETDATE() -- dateStart - date
, DATEADD(DAY, 1, GETDATE()) -- dateUpdate - date
, DATEADD(DAY, 5, GETDATE()) -- dateFinish - date
, 'www.stackoverflow' -- link - varchar(50)
),
('78.188.136.74' -- ipval - varchar(50)
, '.com' -- domain - char(5)
, GETDATE() -- dateStart - date
, DATEADD(DAY, 2, GETDATE()) -- dateUpdate - date
, DATEADD(DAY, 10, GETDATE()) -- dateFinish - date
, 'www.msdn' -- link - varchar(50)
);
INSERT INTO #A
(ipval, domain, dateStart, dateUpdate, dateFinish, link)
VALUES ('30.48.111.20' -- ipval - varchar(50)
, '.com' -- domain - char(5)
, GETDATE() -- dateStart - date
, DATEADD(DAY, 5, GETDATE()) -- dateUpdate - date
, DATEADD(DAY, 10, GETDATE()) -- dateFinish - date
, 'www.msdn' -- link - varchar(50)
),
('30.48.111.20' -- ipval - varchar(50)
, '.com' -- domain - char(5)
, GETDATE() -- dateStart - date
, DATEADD(DAY, 5, GETDATE()) -- dateUpdate - date
, DATEADD(DAY, 10, GETDATE()) -- dateFinish - date
, 'www.gmail' -- link - varchar(50)
);
--First Merge
BEGIN TRAN;
MERGE #A AS T
USING #B AS tmp
ON T.domain = tmp.domain
AND T.link = tmp.link
WHEN NOT MATCHED BY TARGET THEN
INSERT (ipval
, domain
, dateStart
, dateUpdate
, dateFinish
, link
)
VALUES (tmp.ipval
, tmp.domain
, tmp.dateStart
, tmp.dateUpdate
, tmp.dateFinish
, tmp.link
)
WHEN MATCHED THEN
UPDATE SET T.dateUpdate = tmp.dateUpdate
WHEN NOT MATCHED BY SOURCE THEN
UPDATE SET T.dateFinish =''a'';
COMMIT TRAN;
GO
SELECT *
FROM #A;
SELECT *
FROM #B;
--Second Merge
BEGIN TRAN;
MERGE #A AS T
USING #B AS tmp
ON T.domain = tmp.domain
AND T.link = tmp.link
WHEN NOT MATCHED BY TARGET THEN
INSERT (ipval
, domain
, dateStart
, dateUpdate
, dateFinish
, link
)
VALUES (tmp.ipval
, tmp.domain
, tmp.dateStart
, tmp.dateUpdate
, tmp.dateFinish
, tmp.link
)
WHEN MATCHED THEN
UPDATE SET T.dateUpdate = tmp.dateUpdate
WHEN NOT MATCHED BY SOURCE THEN
UPDATE SET T.dateFinish = CAST(GETDATE() AS DATE);
COMMIT TRAN;
GO
SELECT *
FROM #A;
SELECT *
FROM #B;
一個可以理解的錯誤,因爲在TechNet頁面鏈接到您的用途'Target'和'Source'作爲例如表名,從而與'TARGET'和'SOURCE'關鍵字將它們混合。 – Heinzi