Tsql 如何根据条件更新表列?

Tsql 如何根据条件更新表列?,tsql,Tsql,两张表: StoreInfo: UserId uniqueidentifier StoreNo nvarchar UserName nvarchar Password nvarchar UserInfo: UserId uniqueidentifier UserName nvarchar Password nvarchar StoreInfo上的用户ID当前为空。如何根据StoreInfo的用户名和密码与UserInfo中的用户名和密码匹配,使用UserInfo的UserId更新StoreI

两张表:

StoreInfo:
UserId uniqueidentifier
StoreNo nvarchar
UserName nvarchar
Password nvarchar

UserInfo:
UserId uniqueidentifier
UserName nvarchar
Password nvarchar
StoreInfo上的用户ID当前为空。如何根据StoreInfo的用户名和密码与UserInfo中的用户名和密码匹配,使用UserInfo的UserId更新StoreInfo的UserId

下面是我编写的查询,它使用UserInfo中的第一个UserId更新StoreInfo中的整个UserId,因此我知道它是错误的

declare @UserName nvarchar(255)
declare @Password nvarchar(25)
declare @UserId uniqueidentifier

select @UserName = UserName, @Password = Password, @UserId = UserId
from UserInfo

select UserId, Password 
   from FranchiseInfo 
   where UserID = @UserName and Password = @Password

update FranchiseInfo
set UserI = @UserId
这将更新表中未设置UserId的所有行。如果只想更新选定的行,请构建where子句。(我还没有测试过这个,所以要注意拼写错误!)


这将更新表中未设置UserId的所有行。如果只想更新选定的行,请构建where子句。(我还没有测试过这个,所以要注意打字错误!)

更新看起来像这样

update storeinfo
set userid = u.userid
from userinfo u 
inner join storeinfo s on (s.username = u.username and s.password = u.password)
where userid is null

更新将如下所示

update storeinfo
set userid = u.userid
from userinfo u 
inner join storeinfo s on (s.username = u.username and s.password = u.password)
where userid is null

最有效的方法是
更新。。。来自
语法,例如

UPDATE StoreInfo
SET
    UserId = ui.UserId
FROM
    StoreInfo si
    INNER JOIN UserInfo ui ON ui.UserName = si.UserName AND ui.Password = si.Password;

最有效的方法是
更新。。。来自
语法,例如

UPDATE StoreInfo
SET
    UserId = ui.UserId
FROM
    StoreInfo si
    INNER JOIN UserInfo ui ON ui.UserName = si.UserName AND ui.Password = si.Password;

感谢您的解决方案更易于理解。谢谢。您的解决方案更易于理解。过早优化是编程中所有罪恶的根源。过早优化是编程中所有罪恶的根源。