SQL Server Dynamic where clause query

I am trying to create a dynamic query I just to do with linq

from a in Customers
where (string.IsNullOrEmpty(name)? true : a.FirstName == name) && (string.IsNullOrEmpty(last)? true : a.LastName ==  last)
select a;

but now I need to do in on Stored Procedure and I don't want to concatenate for security reason and performance. The most close example I found is this query

declare @Name as varchar(100)
declare @GroupName as varchar(100)

set @Name = ''
set @GroupName = 'Manufacturing'

SELECT TOP (1000) [DepartmentID]
      ,[Name]
      ,[GroupName]
      ,[ModifiedDate]
  FROM [AdventureWorks2017].[HumanResources].[Department]
  where ([Name] = case 
                    when @Name is null or @Name = '' then null
                    else @Name
                end
        ) 
                and 
        (
        [GroupName] = case
                when @GroupName is null or @GroupName = '' then null
                else @GroupName
            end
        )

This almost works. I think this should be the answer but the where clause fails for obvious reason.

I would like the where clause could produce '1=1' if the param "Name" or "GroupName" is null example

@Name = "Somename"
@GroupName  = null
where (Name = @Name) and (1 = 1)
--or
@Name = null
@GroupName  = "Somegruopname"
where (1 = 1) and (GroupName = @GroupName)
--
@Name = null
@GroupName  = null
where (1 = 1) and (1 = 1)

Upvotes: 0

Views: 72

Answers (2)

sam
sam

Reputation: 1985

Please try this:

declare @Name as varchar(100)
declare @GroupName as varchar(100) = 'Manufacturing'


set @Name = LTRIM(RTRIM(@Name))
set @GroupName = 'Manufacturing'

SELECT TOP (1000) [DepartmentID]
      ,[Name]
      ,[GroupName]
      ,[ModifiedDate]
  FROM [AdventureWorks2017].[HumanResources].[Department]
  where ([Name] = coalesce(@Name,'') = '' OR [Name] = @Name)
                and 
        ([GroupName] = coalesce(@GroupName, '') = '' OR [GroupName] = @GroupName)

Upvotes: 0

EdmCoff
EdmCoff

Reputation: 3596

You want it to succeed if the variable is null or empty or a match, so I would just write that in your stored procedure.

WHERE (@FirstName is null OR @FirstName = '' OR [FirstName] = @FirstName) 
 AND (@LastName is null OR @LastName = '' OR [LastName] = @LastName)

Upvotes: 1

Related Questions