两个表:
StoreInfo:
UserId uniqueidentifier
StoreNo nvarchar
UserName nvarchar
Password nvarchar
UserInfo:
UserId uniqueidentifier
UserName nvarchar
Password nvarchar
StoreInfo上的UserId当前为空。如何使用UserInfo的UserId基于StoreInfo的UserName更新StoreInfo的UserId,并且Password与UserInfo中的UserName和Password匹配。
以下是我编写的查询,它使用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
答案 0 :(得分:3)
更新看起来像这样
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
答案 1 :(得分:0)
UPDATE StoreInfo
set UserId = ui.UserId
from StoreInfo si
inner join UserInfo ui
on ui.UserName = si.UserName
and ui.Password = si.Password
where si.UserId is null
这将更新表中未设置UserId的所有行。如果您只想更新选定的行,请构建where子句。 (我没有测试过,所以请注意拼写错误!)
答案 2 :(得分:0)
最有效的方法是UPDATE ... FROM
语法,例如
UPDATE StoreInfo
SET
UserId = ui.UserId
FROM
StoreInfo si
INNER JOIN UserInfo ui ON ui.UserName = si.UserName AND ui.Password = si.Password;