我想從名爲Sorels的表中更新名爲Sorels_ext的表。它們之間的鏈接是Sorels_ext的fkey_id等於Sorels表的identity_column。這是我在Merge聲明中的第一次嘗試,我正在嘗試學習語法。需要合併聲明的幫助
MERGE Sorels_ext AS SORe
USING (select SOR.identity_column, CASE
WHEN left(SOR.FPARTNO, 2) = 'BL' THEN 'Blue'
WHEN left(SOR.FPARTNO, 2) = 'RD' THEN 'Red'
ELSE 'White'
END from Sorels AS SOR)
ON (SORe.fkey_id = SOR.identity_column)
WHEN MATCHED THEN
UPDATE SET SORe.fkey_id = SOR.identity_column, SORe.Color = select SOR.identity_column, CASE
WHEN left(SOR.FPARTNO, 2) = 'BL' THEN 'Blue'
WHEN left(SOR.FPARTNO, 2) = 'RD' THEN 'Red'
ELSE 'White'
END
WHEN NOT MATCHED THEN
INSERT (SORe.fkey_id, SORe.Color) VALUES (SOR.identity_column, SORe.Color = select SOR.identity_column, CASE
WHEN left(SOR.FPARTNO, 2) = 'BL' THEN 'Blue'
WHEN left(SOR.FPARTNO, 2) = 'RD' THEN 'Red'
ELSE 'White'
END);
當我運行它,我得到以下錯誤:
錯誤10/22/2009下午1時38分51秒0:00:00.000的SQL Server數據庫錯誤:關鍵字'附近的語法不正確上'。 46 0
*** ADDED INFO ******
第一修正建議後,代碼如下:
MERGE Sorels_ext AS SORe
USING (select SOR.identity_column, CASE
WHEN left(SOR.FPARTNO, 2) = 'BL' THEN 'Blue'
WHEN left(SOR.FPARTNO, 2) = 'RD' THEN 'Red'
ELSE 'White'
END from Sorels) AS SOR
ON (SORe.fkey_id = SOR.identity_column)
WHEN MATCHED THEN
UPDATE SET SORe.fkey_id = SOR.identity_column, SORe.Color = CASE
WHEN left(SOR.FPARTNO, 2) = 'BL' THEN 'Blue'
WHEN left(SOR.FPARTNO, 2) = 'RD' THEN 'Red'
ELSE 'White'
END
WHEN NOT MATCHED THEN
INSERT (SORe.fkey_id, SORe.Color) VALUES (SOR.identity_column, CASE
WHEN left(SOR.FPARTNO, 2) = 'BL' THEN 'Blue'
WHEN left(SOR.FPARTNO, 2) = 'RD' THEN 'Red'
ELSE 'White'
END);
現在我得到以下錯誤:
錯誤10/22/2009 2:03:29 PM 0:00:00.000 SQL Server數據庫錯誤:MERGE語句中使用的插入列列表不能包含多部分標識符。改用單個零件標識符。 55 0
*******增加了更多的信息****** 後從建議的調整,我有以下幾點:
MERGE Sorels_ext AS SORe
USING (select SOR1.identity_column, CASE
WHEN left(SOR1.FPARTNO, 2) = 'BL' THEN 'Blue'
WHEN left(SOR1.FPARTNO, 2) = 'RD' THEN 'Red'
ELSE 'White'
END as colors from Sorels as SOR1) as SOR
ON (SORe.fkey_id = SOR.identity_column)
WHEN MATCHED THEN
UPDATE SET SORe.fkey_id = SOR.identity_column, SORe.Color = CASE
WHEN left(SOR.FPARTNO, 2) = 'BL' THEN 'Blue'
WHEN left(SOR.FPARTNO, 2) = 'RD' THEN 'Red'
ELSE 'White'
END
WHEN NOT MATCHED THEN
INSERT (fkey_id, Color) VALUES (SOR.identity_column, CASE
WHEN left(SOR.FPARTNO, 2) = 'BL' THEN 'Blue'
WHEN left(SOR.FPARTNO, 2) = 'RD' THEN 'Red'
ELSE 'White'
END);
我得到的錯誤:
錯誤10/22/2009 2:46:51 PM 0:00:00.000 SQL Server數據庫錯誤:無效的列名'FPARTNO'。 56 0
我在做什麼錯?
****我知道了! *****
MERGE Sorels_ext AS SORe
USING (select SOR.identity_column, CASE
WHEN left(SOR.FPARTNO, 2) = 'BL' THEN 'Blue'
WHEN left(SOR.FPARTNO, 2) = 'RD' THEN 'Red'
ELSE 'White'
END as colors from Sorels as SOR) SOR1
ON (SORe.fkey_id = SOR1.identity_column)
WHEN MATCHED THEN
UPDATE SET SORe.fkey_id = SOR1.identity_column, SORe.Color = SOR1.colors
WHEN NOT MATCHED THEN
INSERT (fkey_id, Color) VALUES (SOR1.identity_column, SOR1.colors);
恭喜。 – 2009-10-22 21:07:09
小增加:分配'fkey_id = identity_column'毫無意義,因爲您的查詢已經驗證它們具有相同的值。 – 2011-03-25 22:33:23