我正在创建一个存储过程来搜索表。我有许多不同的搜索字段,所有这些字段都是可选的。有没有办法创建一个存储过程来处理这个?假设我有一个包含四个字段的表:ID,FirstName,LastName和Title。我可以这样做:
CREATE PROCEDURE spDoSearch
@FirstName varchar(25) = null,
@LastName varchar(25) = null,
@Title varchar(25) = null
AS
BEGIN
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
FirstName = ISNULL(@FirstName, FirstName) AND
LastName = ISNULL(@LastName, LastName) AND
Title = ISNULL(@Title, Title)
END
这种作品。但是它会忽略FirstName,LastName或Title为NULL的记录。如果未在搜索参数中指定Title,我想包含Title为NULL的记录 - 对于FirstName和LastName是相同的。我知道我可以用动态SQL做到这一点,但我想避免这种情况。
答案 0 :(得分:249)
基于给定参数动态更改搜索是一个复杂的主题,并且以一种方式对其进行操作,即使只有非常小的差异,也会产生巨大的性能影响。关键是使用索引,忽略紧凑代码,忽略担心重复代码,必须做出好的查询执行计划(使用索引)。
阅读本文并考虑所有方法。您最好的方法取决于您的参数,数据,架构和实际使用情况:
Dynamic Search Conditions in T-SQL by by Erland Sommarskog
The Curse and Blessings of Dynamic SQL by Erland Sommarskog
如果您拥有正确的SQL Server 2008版本(SQL 2008 SP1 CU5(10.0.2746)及更高版本),则可以使用此小技巧实际使用索引:
将OPTION (RECOMPILE)
添加到您的查询see Erland's article上,SQL Server将在创建查询计划之前根据OR
内的(@LastName IS NULL OR LastName= @LastName)
解析CREATE PROCEDURE spDoSearch
@FirstName varchar(25) = null,
@LastName varchar(25) = null,
@Title varchar(25) = null
AS
BEGIN
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
(@FirstName IS NULL OR (FirstName = @FirstName))
AND (@LastName IS NULL OR (LastName = @LastName ))
AND (@Title IS NULL OR (Title = @Title ))
OPTION (RECOMPILE) ---<<<<use if on for SQL 2008 SP1 CU5 (10.0.2746) and later
END
的运行时值。可以使用局部变量和索引。
这适用于任何SQL Server版本(返回正确的结果),但如果您使用的是SQL 2008 SP1 CU5(10.0.2746)及更高版本,则仅包含OPTION(RECOMPILE)。 OPTION(RECOMPILE)将重新编译您的查询,只有列出的verison将根据局部变量的当前运行时值重新编译它,这将为您提供最佳性能。如果不是那个版本的SQL Server 2008,请关闭该行。
{{1}}
答案 1 :(得分:26)
@KM的回答是好的,但未能完全跟进他早期的一些建议;
...,忽略紧凑代码,忽略担心重复代码,...
如果您希望获得最佳性能,那么您应该为可选标准的每种可能组合编写一个定制查询。这可能听起来很极端,如果你有很多可选标准,那么性能往往是努力和结果之间的权衡。实际上,可能存在一组通用的参数组合,可以使用定制查询进行定位,然后针对所有其他组合进行通用查询(根据其他答案)。
CREATE PROCEDURE spDoSearch
@FirstName varchar(25) = null,
@LastName varchar(25) = null,
@Title varchar(25) = null
AS
BEGIN
IF (@FirstName IS NOT NULL AND @LastName IS NULL AND @Title IS NULL)
-- Search by first name only
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
FirstName = @FirstName
ELSE IF (@FirstName IS NULL AND @LastName IS NOT NULL AND @Title IS NULL)
-- Search by last name only
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
LastName = @LastName
ELSE IF (@FirstName IS NULL AND @LastName IS NULL AND @Title IS NOT NULL)
-- Search by title only
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
Title = @Title
ELSE IF (@FirstName IS NOT NULL AND @LastName IS NOT NULL AND @Title IS NULL)
-- Search by first and last name
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
FirstName = @FirstName
AND LastName = @LastName
ELSE
-- Search by any other combination
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
(@FirstName IS NULL OR (FirstName = @FirstName))
AND (@LastName IS NULL OR (LastName = @LastName ))
AND (@Title IS NULL OR (Title = @Title ))
END
这种方法的优点在于,在通过定制查询处理的常见情况下,查询尽可能高效 - 不受限制的标准没有影响。此外,索引和其他性能增强可以针对特定的定制查询,而不是试图满足所有可能的情况。
答案 2 :(得分:25)
您可以在以下情况下执行
CREATE PROCEDURE spDoSearch
@FirstName varchar(25) = null,
@LastName varchar(25) = null,
@Title varchar(25) = null
AS
BEGIN
SELECT ID, FirstName, LastName, Title
FROM tblUsers
WHERE
(@FirstName IS NULL OR FirstName = @FirstName) AND
(@LastNameName IS NULL OR LastName = @LastName) AND
(@Title IS NULL OR Title = @Title)
END
然而,依赖于数据有时会更好地创建动态查询并执行它们。
答案 3 :(得分:8)
扩展您的WHERE
条件:
WHERE
(FirstName = ISNULL(@FirstName, FirstName)
OR COALESCE(@FirstName, FirstName, '') = '')
AND (LastName = ISNULL(@LastName, LastName)
OR COALESCE(@LastName, LastName, '') = '')
AND (Title = ISNULL(@Title, Title)
OR COALESCE(@Title, Title, '') = '')
我。即将不同的情况与布尔条件结合起来。
答案 4 :(得分:6)
晚会五年。
在接受的答案的提供链接中提到,但我认为它应该在SO上得到明确答案 - 基于提供的参数动态构建查询。 E.g:
<强>设置强>
-- drop table Person
create table Person
(
PersonId INT NOT NULL IDENTITY(1, 1) CONSTRAINT PK_Person PRIMARY KEY,
FirstName NVARCHAR(64) NOT NULL,
LastName NVARCHAR(64) NOT NULL,
Title NVARCHAR(64) NULL
)
GO
INSERT INTO Person (FirstName, LastName, Title)
VALUES ('Dick', 'Ormsby', 'Mr'), ('Serena', 'Kroeger', 'Ms'),
('Marina', 'Losoya', 'Mrs'), ('Shakita', 'Grate', 'Ms'),
('Bethann', 'Zellner', 'Ms'), ('Dexter', 'Shaw', 'Mr'),
('Zona', 'Halligan', 'Ms'), ('Fiona', 'Cassity', 'Ms'),
('Sherron', 'Janowski', 'Ms'), ('Melinda', 'Cormier', 'Ms')
GO
<强>程序强>
ALTER PROCEDURE spDoSearch
@FirstName varchar(64) = null,
@LastName varchar(64) = null,
@Title varchar(64) = null,
@TopCount INT = 100
AS
BEGIN
DECLARE @SQL NVARCHAR(4000) = '
SELECT TOP ' + CAST(@TopCount AS VARCHAR) + ' *
FROM Person
WHERE 1 = 1'
PRINT @SQL
IF (@FirstName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @FirstName'
IF (@LastName IS NOT NULL) SET @SQL = @SQL + ' AND FirstName = @LastName'
IF (@Title IS NOT NULL) SET @SQL = @SQL + ' AND Title = @Title'
EXEC sp_executesql @SQL, N'@TopCount INT, @FirstName varchar(25), @LastName varchar(25), @Title varchar(64)',
@TopCount, @FirstName, @LastName, @Title
END
GO
<强>用法强>
exec spDoSearch @TopCount = 3
exec spDoSearch @FirstName = 'Dick'
优点:
缺点:
不是直接回答,而是与问题相关,即大图
通常,这些过滤存储过程不会浮动,而是从某个服务层调用。这样就可以选择将业务逻辑(过滤)从SQL迁移到服务层。
一个例子是使用LINQ2SQL根据提供的过滤器生成查询:
public IList<SomeServiceModel> GetServiceModels(CustomFilter filters)
{
var query = DataAccess.SomeRepository.AllNoTracking;
// partial and insensitive search
if (!string.IsNullOrWhiteSpace(filters.SomeName))
query = query.Where(item => item.SomeName.IndexOf(filters.SomeName, StringComparison.OrdinalIgnoreCase) != -1);
// filter by multiple selection
if ((filters.CreatedByList?.Count ?? 0) > 0)
query = query.Where(item => filters.CreatedByList.Contains(item.CreatedById));
if (filters.EnabledOnly)
query = query.Where(item => item.IsEnabled);
var modelList = query.ToList();
var serviceModelList = MappingService.MapEx<SomeDataModel, SomeServiceModel>(modelList);
return serviceModelList;
}
优点:
缺点:
答案 5 :(得分:-3)
这也有效:
...
WHERE
(FirstName IS NULL OR FirstName = ISNULL(@FirstName, FirstName)) AND
(LastName IS NULL OR LastName = ISNULL(@LastName, LastName)) AND
(Title IS NULL OR Title = ISNULL(@Title, Title))