没有为 'src' 合并语句 SQL 服务器的第 1 列指定列名

No column name was specified for column 1 of 'src' Merge statement SQL server

我在 SQL 服务器中使用 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 创建视图或使用规范名称填充 table。然后将其用于 MERGE 语句。