简体   繁体   English

如何在 SQL Server 中生成并手动插入唯一标识符?

[英]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...我正在尝试在我的表中手动创建一个新用户,但我发现不可能在代码不抛出异常的情况下生成“UniqueIdentifier”类型......

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.引发此异常 -> 消息 8169,级别 16,状态 2,第 4 行 无法将字符串转换为 uniqueidentifier。

I am using the NEWID() method but it's not working...我正在使用 NEWID() 方法,但它不起作用...

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

ApplicationId must be of type UniqueIdentifier . ApplicationId 必须是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.因此,我认为可以安全地假设ApplicationId不是正确的数据类型。

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .请检查表 aspnet_Users 中的列 ApplicationId 数据类型,ApplicationId 列数据类型应为 uniqueidentifier 。

* Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument. *您的参数顺序传递错误,参数@id 应作为第一个参数传递,但在您的脚本中它放在第二个参数中。 . . * *

So error is raised..所以引发了错误..

Please refere sample script:请参考示例脚本:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM