Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting GUID into SQL Server

Tags:

sql

guid

insert

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;

@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?

Thanks guys.

Update Here's the 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 '-'.
like image 431
simplyme Avatar asked Jun 06 '09 14:06

simplyme


2 Answers

Just cast it from a 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
like image 99
Sören Kuklau Avatar answered Sep 22 '22 14:09

Sören Kuklau


You simply need to QUOTE your 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

like image 41
marc_s Avatar answered Sep 19 '22 14:09

marc_s