【问题标题】:Return UniqueIdentifier of newly inserted row返回新插入行的唯一标识符
【发布时间】:2015-04-04 03:36:11
【问题描述】:

我有以下插入语句:

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,但我需要在执行插入语句后返回 NEWID() 值,因为我需要此 NEWID() 用于网站内的其他功能,但我我不确定如何检索它,因为我的 SQL 技能不是很好,我希望有人能帮助我。

【问题讨论】:

标签: sql-server-2008 sql-insert


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    相关资源
    最近更新 更多