2010-07-26 13 views
10

Immaginate un tavolo che assomiglia a questo:Return NEWSEQUENTIALID() come parametro di output

CREATE TABLE [dbo].[test](
    [id] [uniqueidentifier] NULL, 
    [name] [varchar](50) NULL 
) 

GO 

ALTER TABLE [dbo].[test] ADD CONSTRAINT [DF_test_id] DEFAULT (newsequentialid()) FOR [id] 
GO 

Con una stored procedure INSERT che assomiglia a questo:

CREATE PROCEDURE [Insert_test] 
    @name as varchar(50), 
    @id as uniqueidentifier OUTPUT 
AS 
BEGIN 
    INSERT INTO test(
     name 
    ) 
    VALUES(
     @name 
    ) 
END 

Qual è il modo migliore per ottenere il GUID che è stato appena inserito e lo restituisce come parametro di output?

risposta

10

utilizzare la clausola di uscita della dichiarazione Inserisci.

CREATE PROCEDURE [Insert_test] 
    @name as varchar(50), 
    @id as uniqueidentifier OUTPUT 
AS 
BEGIN 
    declare @returnid table (id uniqueidentifier) 

    INSERT INTO test(
     name 
    ) 
    output inserted.id into @returnid 
    VALUES(
     @name 
    ) 

    select @id = r.id from @returnid r 
END 
GO 

/* Test the Procedure */ 
declare @myid uniqueidentifier 
exec insert_test 'dummy', @myid output 
select @myid 
+0

Questo era esattamente quello di cui avevo bisogno. –

0

Prova

SELECT @ID = ID FROM Test WHERE Name = @Name 

(se il nome ha un vincolo Unique)

+2

"(se il nome ha un vincolo Unique)" Non c'è niente nel PO per farci pensare questo è un presupposto valido ed è inutilmente restrittivo. –

Problemi correlati