I am trying to compare a column col1
and a variable @myvar
in a WHERE
clause. Both usually contain GUIDs, but may also have NULL values.
I thought I could get around the fact that NULL=NULL
evaluates to FALSE by using WHERE ISNULL(col1, '')=ISNULL(@myvar, '')
. That would compare two empty strings instead, and evaluate to TRUE.
This will, however, produce the following error message:
Msg 8169, Level 16, State 2, Line 3 Conversion failed when converting from a character string to uniqueidentifier.
I tried
DECLARE @myvar uniqueidentifier = NULL
SELECT ISNULL(@myvar,'') as col1
Same error message.
Two questions: First, I am trying to convert a uniqueidentifier variable - even though it has a NULL value - to an (empty!) string, not the other way around, as the error message suggests. What gives?
Second, is there a better way to word that WHERE clause I need, to allow for comparing uniqueidentifiers that might be NULL?
You can make uniqueidentifiers null. So the problem lies somewhere else. Do you have a trigger on the table or a default on the column that would be causing this?
Yes, we can. The Unique constrain mainly use to restrict duplicate values insertion and ensure that column has a unique value. It will not allow you to enter the duplicate NULL value in the column but allow you to insert a unique(Single) NULL value in the column.
The globally unique identifier (GUID) data type in SQL Server is represented by the uniqueidentifier data type, which stores a 16-byte binary value. A GUID is a binary number, and its main use is as an identifier that must be unique in a network that has many computers at many sites.
There are two functions using which you can create GUIDs in SQL Server – NewID and NewSequentialID. And there's a data type – "uniqueidentifier" which can be used to store GUIDs.
I think below expression can be used to check if the GUID column is empty
CAST(0x0 AS UNIQUEIDENTIFIER)
some thing like
...WHERE GuidId <> CAST(0x0 AS UNIQUEIDENTIFIER)
Since the first argument you are passing isnull
is not a literal null
, it will determine the return type of that call, a uniqueidentifier
in your case. The second argument, ''
, cannot be cast to this type, hence the error you're getting.
One way around this is just to explicitly check for null
s:
WHERE (@myvar IS NULL AND col1 IS NULL) OR (col1 = @myvar)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With