2016-09-06 81 views
0

我在SQL服务器中使用MERGE语句来刷新数据,但是我反复得到这个错误INT MERGE语句的ON子句。 代码是'src'的列1没有指定列名合并语句SQL服务器

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); 

回答

2

您没有为src指定的列名 - 消息是相当清楚的。试试这个:

MERGE [metadata].[Entity] AS trgt 
USING (VALUES(@queryEntity)) AS src(EntityId) 
--------------------------------------^ 

我应该指出这只是个开始。 src也没有大量其他列,在MERGE的其余部分中指定。事实上,它只是一个字符串。 MERGE不会因为它看起来像查询而执行字符串。

您有三种选择。首先是免除变量并将查询字符串放在MERGE中。但这似乎不可能,因为你有可变的标识符名称。

第二个是使用动态SQL与MERGE

不过,我的建议是使用动态SQL来创建视图或使用规范名称填充表。然后将其用于MERGE声明。

+1

我认为op期望他的@queryEntity执行 –