繁体   English   中英

SQL Server 动态 where 子句查询

[英]SQL Server Dynamic where clause query

我正在尝试创建一个动态查询,我只是用 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”为空,我希望 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)

如果变量为空或为空或匹配,您希望它成功,所以我只会在您的存储过程中写下它。

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

请试试这个:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM