问题
When it comes to search record with optional parameter in SQL stored procedure, out of these two queries. Both return the same results. Considering performance, which one will you use and why?
I have a stored procedure which has multiple search parameters and will be searching in multiple tables, with joins from a huge record set.
DECLARE @EventName VARCHAR(100)
--SET @EventName = ''
--SET @EventName = NULL
SET @EventName = 'Coffee in Coffee Bean'
-- Query - 1
SELECT *
FROM EventDetails
WHERE
1 = CASE
WHEN @EventName IS NULL OR @EventName = '' THEN 1
WHEN EventName LIKE '%'+ @EventName +'%' THEN 1 ELSE 0
END
-- Query - 2
SELECT *
FROM EventDetails
WHERE
EventName LIKE '%' + CASE
WHEN LEN(LTRIM(@EventName)) > 0
THEN @EventName
ELSE EventName
END + '%'
回答1:
You can try this by writing a single query
SELECT *
FROM EventDetails
WHERE ((@EventName IS NULL OR @EventName) OR (EventName LIKE '%'+ @EventName +'%'))
回答2:
My money is on this:
IF ISNULL(@EventName), '') = ''
SELECT * FROM EventDetails
ELSE
SELECT * FROM EventDetails WHERE EventName = '%' + @EventName + '%'
回答3:
If you can't consider dynamic SQL, then try to use as less functions and data tampering as possible. The most common approach for this would be something like the following:
DECLARE @OptionalFilter1 INT
DECLARE @OptionalFilter2 VARCHAR(100)
-- ...
DECLARE @OptionalFilterN BIT
SELECT
YourColumns
FROM
YourTable AS T
WHERE
(@OptionalFilter1 IS NULL OR @OptionalFilter1 = T.Filter1Column) AND
(@OptionalFilter2 IS NULL OR @OptionalFilter2 = T.Filter2Column) AND
-- ...
(@OptionalFilterN IS NULL OR @OptionalFilterN = T.FilterNColumn)
For your example would be:
DECLARE @EventName VARCHAR(100) = 'Coffee in Coffee Bean'
SELECT
*
FROM
EventDetails AS E
WHERE
(@EventName IS NULL OR E.Event LIKE '%' + @EventName + '%')
If this is gonna end in a procedure, consider using OPTION (RECOMPILE)
on the query with many filters and/or assigning the stored procedure parameters to new local scope variables to prevent parameter sniffing. You can read about parameter sniffing problem (with an example similar to yours) in this post.
来源:https://stackoverflow.com/questions/50048397/what-is-best-way-to-search-from-optional-parameter-to-sql-query-in-a-stored-proc