Search code examples
sql-servert-sqluniqueidentifier

SQL Server : using unique identifier in Where clause


I ran this query:

select
    *
from
    [dbo].[planservice]
where
    cast([serviceid] as varchar(255)) = cast('49D9161A-B92B-E911-8101-001056B242CB' as varchar(255))

I am not sure why I am getting this error message:

Conversion failed when converting from a character string to a uniqueidentifier

Wouldn't they both be considered strings?

Edit: this does work without the casting, the reason my query did not work is because I had this part before included in my where clause:

a.[planid] = ''

Once I removed that, everything worked fine. The question is, why is that a problem?

Edit: I am not sure why people are marking this to be closed. It works, but I have no idea why it works.


Solution

  • If your serviceid is uniqueidentifier then why are you casting it to varchar(255)? You can simply run

    select
    *
    from
    [dbo].[planservice]
    where [serviceid] = '49D9161A-B92B-E911-8101-001056B242CB' 
    

    This will work fine for uniqueidentifier.