Passing uniqueidentifier parameter to Stored Procedure
Asked Answered
S

3

8

I am trying to pass a uniqueidentifier parameter to a stored procedure using the following code:

myCommand.Parameters.Add("@BlogID", SqlDbType.UniqueIdentifier).Value = "96d5b379-7e1d-4dac-a6ba-1e50db561b04";

I keep getting an error however saying that the program was unable to convert from string to GUID. Am I passing the value incorrectly?

Shoreline answered 30/7, 2012 at 15:31 Comment(4)
are you setting Value to a string representation or a guid?Wobble
it's a string, but it is in the GUID formatShoreline
You say "I give you a Guid!", but you give it a string. No wonder the poor one is confused. Give it a Guid!Zen
There is a constructor for the Guid structure which accepts a string parameter (to convert the string representation of a GUID into a new Guid object). See also Guid(String) Another alternative is to use Guid.Parse() and similar methods.Merlynmermaid
W
34

Try this

myCommand.Parameters.Add("@BlogID", SqlDbType.UniqueIdentifier).Value = new Guid("96d5b379-7e1d-4dac-a6ba-1e50db561b04");
Wobble answered 30/7, 2012 at 15:32 Comment(2)
Downvote because it is missing an explanation. Please explain what is wrong, instead of just saying "Do this."Zen
For VB, with "Option Strict On", the line would look like this paramList.Add(New SqlParameter("@blogID", SqlDbType.UniqueIdentifier) With {.Value = New Guid("96d5b379-7e1d-4dac-a6ba-1e50db561b04")})Inequity
A
8

A unique identifier is a GUID. so it's a different object type to your string.

You need

myCommand.Parameters.Add("@BlogID", SqlDbType.UniqueIdentifier).Value = 
                                        new Guid("96d5b379-7e1d-4dac-a6ba-1e50db561b04");
Anuradhapura answered 30/7, 2012 at 15:33 Comment(0)
R
0

One thing to check is that you are not comparing the uniqueidentifier to any string in the database.

When I ran into this, I found a section where I had the following line:

IF @MyGuid IS NULL OR @MyGuid = '' BEGIN...

The { @MyGuid = '' } part will cause the error you described.

Rightist answered 23/5, 2022 at 18:49 Comment(1)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewPeroxide

© 2022 - 2024 — McMap. All rights reserved.