SQL Server动态where子句查询

时间:2019-12-03 22:10:22

标签: sql sql-server

我正在尝试创建一个与linq有关的动态查询

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

但是现在我需要执行存储过程,并且出于安全原因和性能我不想串联。我找到的最接近的示例是此查询

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
        )

这几乎可行。我认为这应该是答案,但是where子句由于明显的原因而失败。

如果参数“ Name”或“ GroupName”为null,我希望where子句可以产生'1 = 1' 例子

@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)

2 个答案:

答案 0 :(得分:1)

如果变量为null或为空或匹配,则希望它成功执行,因此我将其写入存储过程中。

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

答案 1 :(得分:0)

请尝试以下操作:

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)
相关问题