我有在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 :(得分:1)
您可以更改查询以删除SELECT子查询,只需执行以下操作:
UPDATE CustomerUser
SET LoginName = CONCAT(LoginName, UserName)
-- Other fields, etc..
WHERE ID **IN(1,2,3,4, etc...)**;
如果您在C#中这样做,我建议使用Entity Framework而不是SQL Query字符串。我只将它与SQL Server一起使用,但是这里讨论了与MySQL一起使用的信息:
Using MySQL with Entity Framework
使用Entity,您可以通过编写一个包含所有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();
}
}
答案 1 :(得分: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()