How to generate and manually insert a uniqueidentifier in sql server?

Mehdi Bugnard picture Mehdi Bugnard · Jun 24, 2013 · Viewed 126.2k times · Source

I'm trying to manually create a new user in my table but impossible to generate a "UniqueIdentifier" type without threw 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

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

I use the NEWID() method but it's not work...

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

Answer

Darren picture Darren · Jun 24, 2013

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.