Solved

MSSQL 2014 Returning GUID on Insert via Stored Procedure

Posted on 2016-08-25
8
39 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
  • 5
  • 2
8 Comments
 
LVL 39

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 39

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
 
LVL 39

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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

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 39

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 39

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:ScottPletcher
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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

In this article I will describe the Detach & Attach method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

708 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now