How to insert a NEWID() / GUID / UUID into the code editor?

If you have the SQL Prompt extension installed, you can create a new snippet like so...

Snippet: guid

Description: new GUID

Code:

'$GUID$'

Now type guid in your text editor and you'll get a new GUID surrounded by 's.


NEWID() itself is a function. when called returns a GUID value.

You do not have to put it in a separate window and then copy paste value from there. Just simply put that function there where you want the GUID value and when the query is executed at run time the value returned by this function will be used.

For instance in an Insert statement

INSERT INTO TableName (Col1 , Col2, Col3)
VALUES (1 , 'Value 1', NEWID())  

If you want col3 to have a GUID value you do not need to copy paste the value returned from NEWID() function but you use the function itself. At runtime a guid value will be retuned and inserted into col3.

Similarly if you were updating

UPDATE TableName 
  SET Col3 = NEWID()
WHERE <Some Condition>

Again you dont have to copy paste the value returned from NEWID() function just use the function itself.

Another Option would be suppose you are somewhere inside your code where you cannot call the NEWID() function . You would Declare a variable of type UNIQUEIDENTIFIER call the function store its value to that variable and then use that variable inside you code something like ...

DECLARE @GUID_Value UNIQUEIDENTIFIER;
 SET @GUID_Value = NEWID();

-- Now use this variable anywhere in your code.  

Adding to Keyboard Shortcut

For some strange reason if you want to add a shortcut to your SSMS to generate GUIDs for you. You would need to two thing.

  1. Create a stored Procedure which returns GUID value .
  2. Add a key shortcut to call that stored Procedure.

Proc Definition

CREATE PROCEDURE get_Guid
AS 
 SELECT NEWID();

Add it to shortcuts

From your SSMS goto Tools --> Options --> Environment --> Keyboard

add the stored procedure's name to the shortcut you want to. Click OK. Close SSMS and reopen it again and you are good to go.

enter image description here

As shown in the above snipshot, now if you press CTRL + 0 it will generate a GUID value for you in the same query window.


For SQL server, and maybe others.

One can insert a string-encoded Guid/uuid in SQL server using the convert function. See the zeroed Guid in the example below.

INSERT INTO [schema].[table]
           ([Id]
           ,[stuff])
     VALUES
           (Convert(uniqueidentifier, N'00000000-0000-0000-0000-000000000000')
           ,'Interesting Stuff'
)