Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: ISNULL on uniqueidentifier

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?

like image 334
TVogt Avatar asked Aug 28 '15 23:08

TVogt


People also ask

Can Uniqueidentifier be null in SQL Server?

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?

Can a unique identifier be null?

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.

What data type is Uniqueidentifier SQL Server?

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.

Does SQL support GUID?

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.


2 Answers

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)
like image 59
NidhinSPradeep Avatar answered Sep 22 '22 14:09

NidhinSPradeep


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 nulls:

WHERE (@myvar IS NULL AND col1 IS NULL) OR (col1 = @myvar)
like image 21
Mureinik Avatar answered Sep 21 '22 14:09

Mureinik