Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a new Guid in stored procedure?

I currently have a stored procedure in which I want to insert new rows into a table.

insert into cars (id, Make, Model) values('A new Guid', "Ford", "Mustang") 

So the primary key 'id' is a Guid. I know how to create a new Guid in C# code but within the stored procedure I'm unsure how to generate the new Guids for the primary key values.

like image 497
Mr Cricket Avatar asked Oct 14 '10 22:10

Mr Cricket


People also ask

How do you define a new GUID?

GUIDs are most commonly written in text as a sequence of hexadecimal digits as such, 3F2504E0-4F89-11D3-9A0C-0305E82C3301. Often braces are added to enclose the above format, as such: {3F2504E0-4F89-11D3-9A0C-0305E82C3301}

How do I get a random GUID?

We can generate GUID by calling following code snippet. As you can see from this code, we use Guid. NewGuid() method to generate a new GUID in C#. Note that in above code we have used the NewGuid Method which will create new GUID.

How do I create a unique identifier in SQL?

Use NEWID() to Create a Unique Value in SQL Server More specifically, it's an RFC4122-compliant function that creates a unique value of type uniqueidentifier. The value that NEWID() produces is a randomly generated 16-byte GUID (Globally Unique IDentifier). This is also known as a UUID (Universally Unique IDentifier).

What is GUID generator?

A GUID (globally unique identifier) is a 128-bit text string that represents an identification (ID). Organizations generate GUIDs when a unique reference number is needed to identify information on a computer or network. A GUID can be used to ID hardware, software, accounts, documents and other items.


2 Answers

With SQL Server you can use the function NEWID. You're using C# so I assume that you're using SQL Server. I'm sure other database system have similar functions.

select NEWID() 

If you're using Oracle then you can use the SYS_GUID() function. Check out the answer to this question: Generate a GUID in Oracle

like image 177
Adam Porad Avatar answered Sep 22 '22 03:09

Adam Porad


Try this:

SELECT NewId() 
like image 26
BradB Avatar answered Sep 20 '22 03:09

BradB