Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

MSSQL 2014 Returning GUID on Insert via Stored Procedure

Posted on 2016-08-25
8
Medium Priority
?
170 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 2000 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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 70

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

Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

Question has a verified solution.

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

What if you have to shut down the entire Citrix infrastructure for hardware maintenance, software upgrades or "the unknown"? I developed this plan for "the unknown" and hope that it helps you as well. This article explains how to properly shut down …
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
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

664 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