Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate and manually insert a uniqueidentifier in SQL Server?

I'm trying to manually create a new user in my table but am finding it impossible to generate a "UniqueIdentifier" type without the code throwing an exception...

Here is my example:

DECLARE @id uniqueidentifier SET @id = NEWID()  INSERT INTO [dbo].[aspnet_Users]            ([ApplicationId]            ,[UserId]            ,[UserName]            ,[LoweredUserName]            ,[LastName]            ,[FirstName]            ,[IsAnonymous]            ,[LastActivityDate]            ,[Culture])      VALUES            ('ARMS'            ,@id            ,'Admin'            ,'admin'            ,'lastname'            ,'firstname'            ,0            ,'2013-01-01 00:00:00'            ,'en') GO 

Throws this exception -> Msg 8169, Level 16, State 2, Line 4 Failed to convert a character string to uniqueidentifier.

I am using the NEWID() method but it's not working...

http://www.dailycoding.com/Posts/generate_new_guid_uniqueidentifier_in_sql_server.aspx

like image 621
Mehdi Bugnard Avatar asked Jun 24 '13 11:06

Mehdi Bugnard


People also ask

How do I create a Uniqueidentifier in SQL?

Examples. The following example converts a uniqueidentifier value to a char data type. DECLARE @myid uniqueidentifier = NEWID(); SELECT CONVERT(CHAR(255), @myid) AS 'char'; The following example demonstrates the truncation of data when the value is too long for the data type being converted to.

How do you insert a Uniqueidentifier?

Use the NEWID() function to obtain a globally unique ID (GUID). INSERT INTO THAI_MK_MT_Log(GUID, Status) VALUES (newid(), 'S'). newid() function will generate an unique identifier each time. INSERT INTO THAI_MK_MT_Log(GUID, Status) VALUES (cast ('xxxxxxxx ....

How insert values into Uniqueidentifier column in SQL?

Use the newid() function to populate the global ID or GUID column when you insert a record to the table. Note that you could use the Next_GlobalID stored procedure to get the next ID value.

How do I get Uniqueidentifier in SQL Server?

-- If you want to generate a new Guid (uniqueidentifier) in SQL server the you can simply use the NEWID() function. -- This will return a new random uniqueidentifier e.g. You can directly use this with INSERT statement to insert new row in table.


1 Answers

ApplicationId must be of type UniqueIdentifier. Your code works fine if you do:

DECLARE @TTEST TABLE (   TEST UNIQUEIDENTIFIER )  DECLARE @UNIQUEX UNIQUEIDENTIFIER SET @UNIQUEX = NEWID();  INSERT INTO @TTEST (TEST) VALUES (@UNIQUEX);  SELECT * FROM @TTEST 

Therefore I would say it is safe to assume that ApplicationId is not the correct data type.

like image 55
Darren Avatar answered Sep 24 '22 03:09

Darren