更新并在单个查询中选择

时间:2014-09-06 07:31:57

标签: sql sql-server tsql stored-procedures

我已经写了一个存储过程,我在更新语句中收到错误,请帮我修复它。感谢。

ALTER PROCEDURE [dbo].[UserTransac] 
@SponsorId varchar(20),
@UserId varchar(20),
@SponsorName varchar(50),
@Level int=1

AS
BEGIN
  if not exists(select User_Id from UserTransaction)
    insert into UserTransaction(Sponsor_Id,User_Id,Level_No,Sponsor_Name)
    values(@SponsorId,@UserId,@Level,@SponsorName)
  else
    insert into UserTransaction(Sponsor_Id,User_Id,Level_No,Sponsor_Name)
    values(@SponsorId,@UserId,@Level,@SponsorName)

  insert into UserTransaction(Sponsor_Id,User_Id,Level_No,Sponsor_Name)
  values(@SponsorId,@UserId,@Level+1,@SponsorName)

  update UserTransaction 
  set Sponsor_Id=select Sponsor_Id from Register where User_Id=@UserId

END

3 个答案:

答案 0 :(得分:1)

试试这段代码

UPDATE A
SET A.[Sponsor_Id] = B.[Sponsor_Id]
FROM [UserTransaction] A
INNER JOIN [Register] B ON A.[User_Id] = B.[User_Id]

你也可以在INNER JOIN之后添加WHERE子句

答案 1 :(得分:0)

尝试此查询

update UserTransaction  
set Sponsor_Id = 1 
from Register  
where User_Id = @User_Id

答案 2 :(得分:0)

你只需将选择放在括号内。试试这个。

update UserTransaction set Sponsor_Id=(select Sponsor_Id from Register where User_id=@User_id)

虽然这会更新UserTransaction中所有记录的Sponsor_Id。确保使用适当的where子句仅更新选定的记录。希望这可以帮助。