尝试在SQL Server中使用MERGE
语句并获得以下错误。不确定我在这里可以忽略的是什么。插入值和值计数相同。
INSERT语句中的列多于VALUES子句中指定的值。 VALUES子句中的值数必须与INSERT语句中指定的列数相匹配。
下面的声明
MERGE EHRCLSQL01.NOCAdmin.dbo.ViewOnlyTracking AS vot
USING
(SELECT
@Database AS [Database],
'Copy' AS Mode,
CASE WHEN @Passed = 0 THEN 'Failed' ELSE 'Success' END AS [Status],
@Duration AS Duration,
GETDATE() AS DateTimestamp,
GETDATE() AS LastSuccessDateTimestamp) AS s ON vot.[Database] = s.[Database]
AND vot.Mode = s.Mode
WHEN MATCHED THEN
UPDATE
SET
vot.[Status] = s.[Status]
, vot.Duration = s.Duration
, vot.DateTimestamp = s.DateTimestamp
, vot.LastSuccessDateTimestamp = s.LastSuccessDateTimestamp
WHEN NOT MATCHED THEN
INSERT ([Database], [Mode], [Status], [Duration], [DateTimestamp], [LastSuccessDateTimestamp])
VALUES (s.[Database], s.Mode, s.[Status], s.Duration, s.DateTimestamp, NULL);
更新:
修正了结束]。现在我得到以下
MERGE语句的目标不能是远程表,远程视图或远程表上的视图。
由于我使用目标服务器中的数据并尝试更新链接服务器,我该如何执行此操作?
答案 0 :(得分:3)
您可以使用EXECUTE AT在远程服务器端进行合并声明。
将您的查询放在变量中,使用?作为参数的占位符然后执行。
这样的事情对你有用。
DECLARE @SQL NVARCHAR(MAX) = '
MERGE NOCAdmin.dbo.ViewOnlyTracking AS vot
USING (SELECT ? AS [Database], ''Copy'' AS Mode, CASE WHEN ? = 0 THEN ''Failed'' ELSE ''Success'' END AS [Status], ? AS Duration, GETDATE() AS DateTimestamp, GETDATE() AS LastSuccessDateTimestamp) AS s
ON vot.[Database] = s.[Database]
AND vot.Mode = s.Mode
WHEN MATCHED THEN
UPDATE SET
vot.[Status] = s.[Status]
, vot.Duration = s.Duration
, vot.DateTimestamp = s.DateTimestamp
, vot.LastSuccessDateTimestamp = s.LastSuccessDateTimestamp
WHEN NOT MATCHED THEN
INSERT ([Database], [Mode], [Status], [Duration], [DateTimestamp], [LastSuccessDateTimestamp])
VALUES (s.[Database], s.Mode, s.[Status], s.Duration, s.DateTimestamp, NULL);';
EXEC (@SQL, @Database, @Passed, @Duration) AT EHRCLSQL01;