[英]Error in SQL Server Merge Statement: The column prefix 'Updated' does not match with a table name or alias name used in the query
[英]No column name was specifies for column 1 of 'src' Merge statement SQL server
我在SQL Server中使用MERGE語句刷新數據,但是在MERGE語句的ON子句中反復出現此錯誤。 該代碼是
DECLARE @instance varchar(50)
DECLARE @db varchar (50)
DECLARE @queryEntity nvarchar(max)
SET @instance = (select value from Parameter where name = 'SERVERALIAS')
SET @db = (select value from Parameter where name = 'SERVERDB')
SET @queryEntity = 'Select EntityId,EntityName,CreatedDate,ModifiedDate,Active,TENANTID,PriorityId From [' + @instance + '].[' + @db + '].metadata.Entity Where TENANTID = 1'
MERGE [metadata].[Entity] AS trgt
USING ( VALUES(@queryEntity) ) AS src
ON ( **trgt.EntityId = src.EntityId** )
WHEN matched
--AND trgt.ModifiedDate <= src.ModifiedDate
THEN
-- if the master has a row newer than the client
-- update the client
UPDATE SET trgt.EntityId = src.EntityId,
trgt.EntityName = src.EntityName,
trgt.Createddate = src.CreatedDate,
trgt.ModifiedDate = src.ModifiedDate,
trgt.Active = src.Active,
trgt.TENANTID = src.TENANTID,
trgt.PriorityId = src.PriorityId
WHEN NOT matched BY SOURCE
THEN
DELETE
WHEN NOT matched BY TARGET
THEN
INSERT ( EntityId, EntityName, CreatedDate, ModifiedDate, Active, TENANTID, PriorityId)
VALUES ( src.EntityId, src.EntityName, src.CreatedDate, src.ModifiedDate, src.Active, src.TENANTID, src.PriorityId);
您尚未為src
指定列名-消息很清楚。 嘗試這個:
MERGE [metadata].[Entity] AS trgt
USING ( VALUES(@queryEntity) ) AS src(EntityId)
--------------------------------------^
我應該指出,這僅僅是開始。 src
也沒有在MERGE
的其余部分中指定的其他許多列。 實際上,它僅僅是一個字符串。 MERGE
不僅僅因為它看起來像查詢就執行字符串。
您有三個選擇。 第一種是省去變量,並將查詢字符串放入MERGE
。 但這似乎不可能,因為您具有可變的標識符名稱。
第二種是將動態SQL與MERGE
一起使用。
不過,我的建議是使用動態SQL創建視圖或使用規范名稱填充表。 然后將其用於MERGE
語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.