Skip to content
Advertisement

Showing conditional Where Condition in SQL SERVER

I am trying to achieve something like this.

SELECT Name, Age From Employee 
WHERE ID=1 
AND CASE(WHEN backguid='00000000-0000-0000-0000-000000000000' 
THEN (State=@state and City = @city) 
ELSE (buildingID=backguid) 
END

I wanted to show state and city column in the where clause only when backguid is empty i.e. 00000000-0000-0000-0000-000000000000. Else I want to show only one column i.e. buildingID=backguid

Overall code that I used here is :

DECLARE 
@firstName varchar(50),
@buildingID XML='<items><item ID="76BA34CE-273A-46AC-B4EF-C99A3E93DD21" /></items>',
@fetchedBuildValue uniqueidentifier,
@State VARCHAR(50) ='WA',
@city VARCHAR(50) ='Spokane'

set @fetchedBuildValue = (SELECT data.item.value('./@ID', 'uniqueidentifier') AS PId
FROM @buildingID.nodes('/items/item') data(item));
SELECT
PortalUser.[ID]
,PortalUser.[Status]
,PortalUser.[Type]
,PortalUser.[Prefix]
,PortalUser.[Suffix]
,PortalUser.[FirstName]
,PortalUser.[MiddleName]
,PortalUser.[LastName]
,PortalUser.[Title]
,PortalUser.[Department]
,PortalUser.[URL]
,PortalUser.[TenantID]
,PortalUser.[DefaultPropertyID]
,PortalUser.[DoNotEmail]
,PortalUser.[Profile]
,PortalUser.[PrimaryPhoneNumberType]
,PortalUser.[PrimaryPhoneNumber]
,PortalUser.[BusinessPhoneNumber]
,PortalUser.[HomePhoneNumber]
,PortalUser.[MobilePhoneNumber]
,PortalUser.[FaxPhoneNumber]
,Building.BuildingName
FROM 
PortalUser
INNER JOIN Relationship AS T_U ON T_U.Target = PortalUser.ID AND T_U.TargetType = 0 AND T_U.SourceType = 6
INNER JOIN Tenant ON T_U.Source = Tenant.ID
WHERE
(@firstname IS NULL OR PortalUser.FirstName LIKE '%' + @firstname + '%')
AND CASE(WHEN @fetchedBuildValue ='00000000-0000-0000-0000-000000000000' 
THEN (State=@state AND City = @city) 
ELSE (buildingID=backguid) 
END

However, I am not able to achieve it via Case. I dont know what I am missing.

Advertisement

Answer

This may help

SELECT Name, Age From Employee 
WHERE ID=1 AND (
   (backguid='00000000-0000-0000-0000-000000000000'  and State=@state and City = @city)
OR ( backguid !='00000000-0000-0000-0000-000000000000' and buildingID=backguid)
)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement