How to create a new guid in a 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") 

Thus, the primary key 'id' is Guid. I know how to create new Guid code in C #, but within a stored procedure. I am not sure how to create new Guides for primary key values.

Can someone help me?

Thank!

+65
sql sql-server stored-procedures
Oct 14 '10 at 22:30
source share
4 answers

With SQL Server, you can use the NEWID function. You are using C #, so I assume you are using SQL Server. I am sure that other database systems have similar features.

 select NEWID() 

If you are using Oracle, you can use the SYS_GUID() function. Answer this question: Create a GUID in Oracle

+132
Oct 14 '10 at 22:33
source share

Try the following:

 SELECT NewId() 
+24
Oct 14 '10 at 22:33
source share

You did not ask about this in your question, but I think it's worth noting that using a GUID for a primary key is not always a good idea. Although simple, it can affect performance when the GUID is used in an index. Have you considered using the Identity column , which is an integer value instead?

Here are some articles that may be helpful to read.

+11
Oct 14 '10 at 22:51
source share

In MySQL, this is UUID (). so the query will look like this:

 insert into cars (id, Make, Model) values(UUID(), "Ford", "Mustang") 

If you want to reuse uuid, you can do it like this:

 set @id=UUID(); insert into cars (id, Make, Model) values(@id, "Ford", "Mustang"); select @id; 
+1
Feb 25 '16 at 12:28
source share



All Articles