Many code editors have a built-in menu item or keyboard function to get a UUID, for example when I press CTRL + SHIFT + G in Delphi it inserts a GUID at the current position in the source code.
I know that I can use SELECT NEWID()
to generate a UUID, but I have to go to the query result, copy the generated UUID to my clipboard (killing whatever was in there before) and then go back to the code and replace the query which is an awful way of dealing with this.
Is there any function (maybe using IntelliSense code snippets?) to do this in SQL Server Management Studio that I haven't found yet?
Some background on why I need this function, I often write SQL Scripts like this:
INSERT INTO table (table_id, value)
VALUES ('112C8DD8-346B-426E-B06C-75BBA97DCD63', 'ABC');
I can't use just call NEWID()
, because I later (in another file) want to refer to the specific row using:
WHERE table_id = '112C8DD8-346B-426E-B06C-75BBA97DCD63'
How can I insert a UUID into the code editor?
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.
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.
CREATE PROCEDURE get_Guid
AS
SELECT NEWID();
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.
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.