代码之家  ›  专栏  ›  技术社区  ›  Pinu

返回值的SQL Server查询

  •  0
  • Pinu  · 技术社区  · 15 年前

    下面是我的查询,它正在更新用户表中的一条记录,我希望查询返回更新后的用户ID,我该怎么做?

             UPDATE USER
                SET GroupID = @New_GroupID
               FROM USER 
    LEFT OUTER JOIN DOCUMENTS ON User.UserID = Documents.UserID
              WHERE (Documents.UNC = @UNC) 
                AND (User.GroupID = @Old_GroupID)
    
    3 回复  |  直到 15 年前
        1
  •  2
  •   CJM    15 年前

    [抓取上一个答案-我阅读插入而不是更新]

    您的查询总是只更新一行吗?

    Declare @ID int
    
    SELECT @ID=User.UserID
    FROM User 
    LEFT OUTER JOIN Documents ON User.UserID = Documents.UserID
    WHERE     (Documents.UNC = @UNC) AND (User.GroupID = @Old_GroupID)
    
    UPDATE User
    Set GroupID = @New_GroupID
    Where UserID = @ID
    
    If @@RowCount = 1
     Return @ID
    Else
     Return -1  /* problem - multiple rows updated */
    
        2
  •  4
  •   OMG Ponies    15 年前

    对于SQL Server 2005+,可以使用 OUTPUT clause :

    UPDATE USER
       SET GroupID = @New_GroupID
    OUTPUT INSERTED.id AS ID
         FROM USER u
    LEFT JOIN DOCUMENTS d ON d.userid = u.userid
        WHERE d.UNC = @UNC 
          AND u.GroupID = @Old_GroupID
    
        3
  •  0
  •   AllenG    15 年前

    如果userid是您的标识列,请添加 Select @@Scope_Identity 在当前更新语句之后。

    如果没有,您只需要稍作修改:

    Update User
    Set GroupID = @New_GroupID
    FROM  User LEFT OUTER JOIN
          Documents ON User.UserId = Documents.UserID
    WHERE Documents.UNC = @UNC AND User.GroupID = @Old_GroupID
    
    Select UserId from User where [YourIdentityColumn] = @@Scope_Identity