Check for empty GUID in SQL

Sql ServerTsql

Sql Server Problem Overview


How do I check if an argument in a stored procedure is an empty GUID or not?

Sql Server Solutions


Solution 1 - Sql Server

SELECT CAST(CAST(0 AS BINARY) AS UNIQUEIDENTIFIER)

That should return your empty guid.

... or even shorter, saving one cast:

SELECT CAST(0x0 AS UNIQUEIDENTIFIER)

So to check for that, you would do

IF @GuidParam = CAST(CAST(0 AS BINARY) AS UNIQUEIDENTIFIER)
BEGIN
   --Guid is empty
END

Solution 2 - Sql Server

Since the empty guid never changes, the other obvious way is to simply use 00000000-0000-0000-0000-000000000000 rather than calculating it.

If @Param = '00000000-0000-0000-0000-000000000000'
...

Or, if in an procedure, you can set a parameter to act as a constant:

Declare @EmptyGuid uniqueidentifier
Set @EmptyGuid = '00000000-0000-0000-0000-000000000000'

Or you could create a scalar user-defined function which simply returns the above constant value (or recalculates it as in Meiscooldude solution).

Solution 3 - Sql Server

DECLARE @EmptyGuid UNIQUEIDENTIFIER = 0x0
DECLARE @NonEmpty UNIQUEIDENTIFIER = NEWID()
IF @EmptyGuid = 0x0 PRINT 'Empty'
IF @NonEmpty = 0x0 PRINT 'Empty' ELSE PRINT 'NonEmpty'

Will print

Empty

NonEmpty

Solution 4 - Sql Server

You can make Empty Guid like this:

DECLARE @EmptyGuid UNIQUEIDENTIFIER
SET @EmptyGuid = (SELECT CAST(CAST(0 AS BINARY) AS UNIQUEIDENTIFIER))

-- Single result is 00000000-0000-0000-0000-000000000000
SELECT @EmptyGuid

Solution 5 - Sql Server

Use

DECLARE @param UNIQUEIDENTIFIER = NEWID();
--DECLARE @param UNIQUEIDENTIFIER = '00000000-0000-0000-0000-000000000000'

IF (CONVERT(UNIQUEIDENTIFIER, 0x00)) = @param
    PRINT 'Empty';
ELSE
    PRINT 'Not Empty';

Solution 6 - Sql Server

DECLARE @SupplierDataHubId  uniqueidentifier=null

 set @SupplierDataHubId=(select HubId from dbo.tblSupplierData where fldUpc='603259049389' OR   fldEan='6032590493895555')
if (@SupplierDataHubId is not null)
 begin                 
 print('yes');
end

else 
print 'no'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhovkarView Question on Stackoverflow
Solution 1 - Sql ServerMeiscooldudeView Answer on Stackoverflow
Solution 2 - Sql ServerThomasView Answer on Stackoverflow
Solution 3 - Sql ServerMihail ShishkovView Answer on Stackoverflow
Solution 4 - Sql ServerB.HabibzadehView Answer on Stackoverflow
Solution 5 - Sql ServerVahid FarahmandianView Answer on Stackoverflow
Solution 6 - Sql Serversolanki devView Answer on Stackoverflow