将 GUID 插入 SQL Server

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/959826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 02:20:41  来源:igfitidea点击:

Inserting GUID into SQL Server

sqlinsertguid

提问by simplyme

I have a stored proc were I want to insert a GUID (user id) into a table in MS SQL but I keep getting an error about the hyphen '-' that is part of the guid value, here's my proc defined below;

我有一个存储过程,我想在 MS SQL 中的表中插入一个 GUID(用户 ID),但我一直收到关于连字符“-”的错误,这是 guid 值的一部分,这是我的过程定义如下;

@userID uniqueidentifier,
@bookID int,
@dateReserved datetime,
@status bit

INSERT INTO Reservation(BookId, DateReserved, [Status], UserId)
VALUES (@bookID, @dateReserved, @status, @userID)

But when I put single quotes around the value if the stored proc is executed in Management Studio, it runs fine. How can I handle the guid insertion without problems from my stored proc?

但是,如果存储过程在 Management Studio 中执行,当我在值周围加上单引号时,它运行良好。如何处理 guid 插入而不会出现存储过程中的问题?

Thanks guys.

谢谢你们。

UpdateHere's the sql exec

更新这是 sql exec

DECLARE @return_value int

EXEC    @return_value = [dbo].[usp_ReserveBook]
    @userID = AE019609-99E0-4EF5-85BB-AD90DC302E70,
    @bookID = 7,
    @dateReserved = N'09/03/2009',
    @status = 1

SELECT  'Return Value' = @return_value

Here's the error message

这是错误信息

Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '-'.

回答by S?ren Kuklau

Just cast it from a varchar.

只需从 varchar 投射它。

DECLARE @return_value int

EXEC    @return_value = [dbo].[usp_ReserveBook]
        @userID = CONVERT(uniqueidentifier, 'AE019609-99E0-4EF5-85BB-AD90DC302E70'),
        @bookID = 7,
        @dateReserved = N'09/03/2009',
        @status = 1

SELECT  'Return Value' = @return_value

回答by marc_s

You simply need to QUOTEyour GUID:

您只需要引用您的 GUID:

DECLARE @return_value int

EXEC    @return_value = [dbo].[usp_ReserveBook]
        @userID = 'AE019609-99E0-4EF5-85BB-AD90DC302E70',  
        @bookID = 7,
        @dateReserved = N'09/03/2009',
        @status = 1

SELECT  'Return Value' = @return_value

Marc

马克

回答by Jody

You need single quotes around your GUID....it's just a string to sql server.

你需要在你的 GUID 周围加上单引号......它只是 sql server 的一个字符串。

You could try letting the sp generate the GUID with the sql function newid() ...sql server only i think.

您可以尝试让 sp 使用 sql 函数 newid() ...仅我认为的 sql server 生成 GUID。

And if you're pulling the GUID from another table, let the SP go get that GUID from that table.

如果您要从另一个表中提取 GUID,请让 SP 从该表中获取该 GUID。

回答by James Stewart

Try using this:

尝试使用这个:

sql_cmd.Parameters.AddWithValue
("@Company_ID",**Guid.Parse**("00000000-0000-0000-0000-000000000000");

That will take a simple string rep. and turn it into a GUID obj.

这将需要一个简单的字符串代表。并将其转换为 GUID 对象。