Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

MSSQL 2014 Returning GUID on Insert via Stored Procedure

Posted on 2016-08-25
8
Medium Priority
?
211 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 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
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

 
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

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

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.
Microsoft Access has a limit of 255 columns in a single table; SQL Server allows tables with over 255 columns, but reading that data is not necessarily simple.  The final solution for this task involved creating a custom text parser and then reading…
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.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

885 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