我不完全确定如何表达这一点,所以如果不清楚,请务必让我澄清一些事情。这就是我想要做的事情:
ALTER PROCEDURE UpdateUserProfiles
@userId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON;
SET oldUser = (SELECT TOP 1
FirstName
FROM OldUsers WHERE UserId = @userId);
UPDATE NewUsers
SET FirstName = oldUser.FirstName
WHERE Id = @userId;
END
GO
现在显然这不起作用,但我如何在SP中使用一行?谢谢。
答案 0 :(得分:3)
您可以删除存储过程的用法,而是执行此操作:
UPDATE NewUsers
SET FirstName = (SELECT TOP 1 FirstName
FROM OldUsers WHERE UserId = @userId)
WHERE Id = @userId;
<强>更新强>
由于您要更新多个列,因此最好使用已更新的联接:
update usr
set nus.Firstname = ous.FirstName,
nus.Lastname = ous.LastName
from NewUsers nus
inner join OldUsers ous
on nus.UserId = ous.UserId
where nus.UserId = @userId
原始问题
即使这里的建议解决了您的问题,我们也从未真正告诉您存储过程出了什么问题。好吧,你不再需要了,但总有时间学习!这是(现已弃用)存储过程的固定版本:
ALTER PROCEDURE UpdateUserProfiles
@userId UNIQUEIDENTIFIER
AS
BEGIN
SET NOCOUNT ON;
declare @oldUser UNIQUEIDENTIFIER;
SET @oldUser = (SELECT TOP 1
FirstName
FROM OldUsers WHERE UserId = @userId);
UPDATE NewUsers
SET FirstName = @oldUser
WHERE Id = @userId;
END
GO
你错过了@oldUser
的声明。此外,@oldUser
仅保留FirstName
,因此oldUser.FirstName
没有意义。
答案 1 :(得分:2)
这对你有帮助吗?
UPDATE u
SET FirstName = o.FirstName
FROM NewUsers U
JOIN
OldUsers o on
o.Id = u.id
WHERE
U.ID = @userId
以下是Adrians脚本的一种变体,可以一次更新所有行:
UPDATE u
SET FirstName =
(select top 1 FirstName
from OldUsers
where UserId = u.UserId
)
FROM NewUsers u