Solved

MSSQL 2014 Returning GUID on Insert via Stored Procedure

Posted on 2016-08-25
8
116 Views
Last Modified: 2016-08-25
I was wondering what i need to do to get the just inserted GUID from a new Record.
My table has a guid column which has a default value of NewID() . Below is my stored
Procedure. If i can insert just fine but dont get the GUID back

CREATE PROCEDURE tbl_Address_INS
(
	@Guid uniqueidentifier OUTPUT,
	@Version                            smallint,
	@CustomerId                         varchar(15),
	@CustomerName                       nchar(32),
	@CreatedOn                          datetime,
	@CreatedBy                          nchar(10)
)
AS
	INSERT INTO dbo.tbl_Address	(
		Version,
		CustomerId,
		CustomerName,
		CreatedOn,
		CreatedBy)
	VALUES	
	(
		@Version,
		@CustomerId,
		@CustomerName,
		@CreatedOn,
		@CreatedBy
	)

Open in new window

0
Comment
Question by:AlexPonnath
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 2
8 Comments
 
LVL 40

Expert Comment

by:lcohan
ID: 41770772
You can get the GUID back by using OUTPUT clause in your SP and this will work when you're inserting multiple records also.
so you will add the command below after your insert but which column name is the actual GUID as I can't see CustomerId varchar(15) holding GUID data.
......
OUTPUT inserted.Guid
......
0
 
LVL 40

Accepted Solution

by:
lcohan earned 500 total points
ID: 41770778
Something like in this example:


CREATE TABLE dbo.TestTable (
    ColGuid uniqueidentifier NOT NULL DEFAULT NewSequentialID(),
    Col2    int              NOT NULL
)
GO

DECLARE @op TABLE (ColGuid uniqueidentifier)

INSERT INTO dbo.TestTable (Col2)
OUTPUT inserted.ColGuid
INTO @op -- so this is where you put the inserted/generated GUID or GUIDs
VALUES (1)

SELECT * FROM @op -- then you output whether is one or a bunch of them.

SELECT * FROM dbo.TestTable
GO
0
 

Author Comment

by:AlexPonnath
ID: 41770797
So based on your code it seems you are creating a temp table @op and then query @op to get the value ? Is there no way to directly return the  inserted.ColGuid
0
Instantly Create Instructional Tutorials

Contextual Guidance at the moment of need helps your employees adopt to new software or processes instantly. Boost knowledge retention and employee engagement step-by-step with one easy solution.

 
LVL 40

Expert Comment

by:lcohan
ID: 41770819
Not realy - is either you declare a variable uniqueidentifier and SET that = NEWID() then insert the value from it then return it at the end OR like in example above that can deal with multiple INSERTed rows in one command.
There are some options where people used triggers(yak!) to PRINT the inserted value but I would never add a trigger on any table (in particular dealing with GUIDS - slowest Microsoft data type - well other than NTEXT) to slow down the insert.
0
 

Author Comment

by:AlexPonnath
ID: 41770833
Only problem is how to access the returned guid from a vb.net ExecuteNonQuery since it doesn't return
any queryResult only Output Parm
0
 
LVL 40

Expert Comment

by:lcohan
ID: 41770844
if you want to read the value from a .Net client. you would just use the ExecuteScalar method something like:
...
string sql = "INSERT INTO GuidTest(IntColumn) OUTPUT inserted.GuidColumn VALUES(1)";
SqlCommand cmd = new SqlCommand(sql, conn);
Guid guid = (Guid)cmd.ExecuteScalar();
...
0
 
LVL 40

Expert Comment

by:lcohan
ID: 41770849
OR... you can fill a SqlDataReader to store the GUIDs and use it from there right?
0
 
LVL 69

Expert Comment

by:Scott Pletcher
ID: 41770888
You can use OUTPUT to return a result set from the stored proc (rather than as an OUTPUT parameter):

CREATE PROCEDURE tbl_Address_INS
(
      @Guid uniqueidentifier OUTPUT,
      @Version                            smallint,
      @CustomerId                         varchar(15),
      @CustomerName                       nchar(32),
      @CreatedOn                          datetime,
      @CreatedBy                          nchar(10)
)
AS
      INSERT INTO dbo.tbl_Address      (
            Version,
            CustomerId,
            CustomerName,
            CreatedOn,
            CreatedBy)
        OUTPUT INSERTED.guid
      VALUES      
      (
            @Version,
            @CustomerId,
            @CustomerName,
            @CreatedOn,
            @CreatedBy
      )
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to shrink a transaction log file down to a reasonable size.

631 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question