2017-04-24 55 views
0

我有,在C#中运行,该代码的功能代码:更新使用自定义值

遍历用户列表和更新表中的行。

UPDATE CustomerUser 
       SET 
        LoginName = @LoginName, 
        UserName = @UserName,  
        IsActive = @IsActive, 
        IsDeleted = @IsDeleted, 
        DeletedDate = @DeletedDate, 
        Modified = CURRENT_TIMESTAMP() 
       WHERE ID = @CustomerUserID; 

在c#代码中,它然后做一些连接到LoginName和userName列。

我想用一个SQL语句替换那个慢的C#进程,它执行类似下面的操作。我对SQL有足够的了解,认为我所要求的可能会完全疯狂,但直到你问的时候才会知道。

UPDATE CustomerUser 
        SET 
         LoginName = select concat(login,uniqueid) from CustomerUser where id **this would be an ID that is in the IN() of parent query** 
         UserName = @UserName,  
         IsActive = @IsActive, 
         IsDeleted = @IsDeleted, 
         DeletedDate = @DeletedDate, 
         Modified = CURRENT_TIMESTAMP() 
        WHERE ID **IN(1,2,3,4, etc...)**; 
+0

请更新你用正确的数据样本和预期的结果质疑 – scaisEdge

回答

1

您可以更改您的查询,以除去SELECT子查询,只是做:

UPDATE CustomerUser 
SET LoginName = CONCAT(LoginName, UserName) 
-- Other fields, etc.. 
WHERE ID **IN(1,2,3,4, etc...)**; 

如果你在C#我这样做会建议使用实体框架而不是SQL查询字符串。我只在SQL Server中使用它,但使用它与MySQL的信息在这里讨论:

Using MySQL with Entity Framework

有了实体,那么您可以使用所有的ID列表更新为写一个函数实现这一点一个parmeter:

void UpdateCustomerUsers(ICollection<int> ids) 
{ 
using (var context = new MyDbContext()) 
{ 
    var customerUsers = context.CustomerUsers.Where(cu => ids.Contains(cu.ID)); 

    foreach (var cu in customerUsers) 
    { 
     cu.LoginName = cu.LoginName + cu.UserName; 
     cu.Modified = DateTime.Now; 
     // and so on... 
    } 

    context.SaveChanges(); 
} 
} 
+0

不知道Ÿ谁做这个开发者选择生内嵌SQL,但是我想移动或刚刚更新的内联SQL现在,整个过程已经预定要重写,但性能现在需要改进。 – ChampChris

0

您可以使用更新加入

UPDATE CustomerUser as t1 
    INNER JOIN ( 
      id from CustomerUser WHERE ID IN(1,2,3,4, etc...) 
) t2 on t1.ID=t2.id 
    SET 
     LoginName = select concat(t1.login, t1.uniqueid) 
     UserName = @UserName,  
     IsActive = @IsActive, 
     IsDeleted = @IsDeleted, 
     DeletedDate = @DeletedDate, 
     Modified = CURRENT_TIMESTAMP()