使用merge如何使用where语句?

时间:2016-06-11 16:54:48

标签: c# sql

我正在使用此代码:

SqlCommand cmd = new SqlCommand(@"
MERGE customermaster  AS target USING
      Tamio.dbo.memberform  AS source
      ON target.id  = source.id 
WHEN MATCHED THEN
    UPDATE SET target.name = source.name
WHEN NOT MATCHED THEN
        INSERT (id, name) VALUES (source.id, source.name)
", conn);
cmd.ExecuteNonQuery();

示例:如何在active = 1的情况下执行mycode。

2 个答案:

答案 0 :(得分:1)

现在无法测试,但如果我记得很清楚,这可能是达到目标的另一种方式

WITH Source AS
(
    SELECT id, name 
    FROM Tamio.dbo.memberform  
    WHERE active = 1
)
MERGE INTO customermaster AS target
USING Source ON target.id = source.id 
WHEN MATCHED THEN
    UPDATE SET target.name = source.name
WHEN NOT MATCHED THEN
    INSERT (id, name) VALUES (source.id, source.name);

但是,所有这些都取决于您要使用Active = 1过滤哪个表。从您的问题不清楚Active是否是客户管理员的字段或成员字段。在我的回答中,我认为这是一个成员形式的领域。

答案 1 :(得分:0)

您应该能够使用子查询:

MERGE (SELECT cm.*
       FROM customermaster cm
       WHERE cm.active = 1
      ) AS target USING
      Tamio.dbo.memberform  AS source
      ON target.id  = source.id 
WHEN MATCHED THEN
    UPDATE SET target.name = source.name
WHEN NOT MATCHED THEN
        INSERT (id, name) VALUES (source.id, source.name);

我假设您使用的是SQL Server,active位于主表中。