Solved

MSSQL 2014 Returning GUID on Insert via Stored Procedure

Posted on 2016-08-25
8
65 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 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
Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

 
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

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

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

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

821 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