返回新插入行的UniqueIdentifier

时间:2015-04-04 03:36:12

标签: sql-server-2008 sql-insert

我有以下插入声明:

INSERT INTO [User].User_Profile

 (UniqueId, Username, EmailAddress,
  Password, BirthDay, BirthMonth,
  BirthYear, Age, AccountType, DateCreated,
  DeletedDate, DeletedReason, ProfileStatus)

  VALUES

  (NEWID(), @Username, @EmailAddress,
  @Password, @BirthDay, @BirthMonth,
  @BirthYeat, @Age, 1, SYSDATETIME(),
  null, null, 2)

  SELECT @@IDENTITY

@@ IDENTITY为我返回特定用户新插入的行ID,但是我需要在执行insert语句后返回NEWID()值,因为我需要这个NEWID()来获取网站内的其他功能但是我和#39;我不确定如何检索它,因为我的SQL技能不是很好我希望有人可以帮助我。

1 个答案:

答案 0 :(得分:1)

使用OUTPUT子句:

INSERT INTO [User].User_Profile

 (UniqueId, Username, EmailAddress,
  Password, BirthDay, BirthMonth,
  BirthYear, Age, AccountType, DateCreated,
  DeletedDate, DeletedReason, ProfileStatus)

OUTPUT INSERTED.UniqueId
  VALUES

  (NEWID(), @Username, @EmailAddress,
  @Password, @BirthDay, @BirthMonth,
  @BirthYeat, @Age, 1, SYSDATETIME(),
  null, null, 2)

它也可以插入到这样的表中:

declare @output(id uniqueidentifier)
 INSERT INTO [User].User_Profile

     (UniqueId, Username, EmailAddress,
      Password, BirthDay, BirthMonth,
      BirthYear, Age, AccountType, DateCreated,
      DeletedDate, DeletedReason, ProfileStatus)

    OUTPUT INSERTED.UniqueId into @output(id)
      VALUES

      (NEWID(), @Username, @EmailAddress,
      @Password, @BirthDay, @BirthMonth,
      @BirthYeat, @Age, 1, SYSDATETIME(),
      null, null, 2)