Creating SQL Server GUID

Question: Write a SQL Stored Procedure to create a GUID and add it to a table. Make that GUID an OUTPUT of that Procedure

Questions by krypt83

Showing Answers 1 - 6 of 6 Answers

GUIDs are created by the newid() function. If the default of the primary key is set to NewID(),a new GUID is generated for any new row. In addition, the newid() function may be declared within an insert/values list. The newid() function will even work as an expression in an insert/select that selects multiple rows. Within stored procedures or front-end code, the function may be called and the GUID stored in a variable. The variable is then used in the insert/values statement and inserted into the new row.

USE db_SUTANU

Create table TBL_USER(USER_ID UniqueIdentifier default NewId(),USER_NAME nvarchar(50))

The next three queries insert a GUID, each using a different method of generating the GUID:
-- GUID from Default (the columns default is NewID())
INSERT db_SUTANU.dbo.[TBL_USER]
(USER_ID, USER_NAME)
VALUES (DEFAULT, ‘Debasis’)


-- GUID from function
INSERT db_SUTANU.dbo.[TBL_USER]
(USER_ID, USER_NAME)
VALUES (NewID(), ‘SUTANU’)


-- GUID in variable
DECLARE @NewGUID UniqueIdentifier
SET @NewGUID = NewID()


INSERT db_SUTANU.dbo.[TBL_USER]
(USER_ID, USER_NAME)
VALUES (@NewGUID, ‘Madhumita’)



To view the results of the previous three methods of inserting a GUID.
SELECT USER_ID, USER_NAME
FROM db_SUTANU.dbo.[TBL_USER]



             USER_ID                                                              USER_NAME
------------------------------------                                         -----------------------
25894DA7-B5BB-435D-9540-6B9207C6CF8F                       Debasis
393414DC-8611-4460-8FD3-4657E4B49373                       SUTANU
FF868338-DF9A-4B8D-89B6-9C28293CA25F                     Madhumita

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions