2015-04-04 56 views
0

歸來唯一標識符,我有以下插入語句:新插入

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技能不是很好,我希望有人能幫助我。

+2

使用OUTPUT子句 – 2015-04-04 03:43:08

+0

我也建議使用**'SCOPE_IDENTITY()' **而不是其他任何東西來抓取新插入的身份值。 [請參閱此博客文章,瞭解有關WHY的解釋](http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity -of-記錄/) – 2015-04-04 06:30:30

回答

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)