Imagine a table that looks like this:
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
With an INSERT stored procedure that looks like this:
CREATE PROCEDURE [Insert_test]
    @name as varchar(50),
    @id as uniqueidentifier OUTPUT
AS
BEGIN
    INSERT INTO test(
        name
    )
    VALUES(
        @name
    )
END
What is the best way to get the GUID that was j开发者_JS百科ust inserted and return it as an output parameter?
Use the Output clause of the Insert statement.
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
Try
SELECT @ID = ID FROM Test WHERE Name = @Name
(if Name has a Unique constraint)
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论