I have a dynamic stored procedure and have to add where clause dynamically in case statement in SQL Server 2008.
My procedure is as below: –
CREATE PROCEDURE SPGETDATA
@STRNAME NVARCHAR(100),
@STRCODE NVARCHAR(100)
AS
BEGIN
SELECT myTable.*
FROM myTable
WHERE
IsDELETED = 0
AND STRNAME LIKE CASE WHEN (RTRIM(LTRIM(@STRNAME))) <> '' THEN
'%'+ @STRNAME + '%' ELSE '%%' END
AND STRCODE LIKE CASE WHEN (RTRIM(LTRIM(@STRCODE)) <> '') THEN
'%' + @STRCODE + '%' ELSE '%%' END**
END
The user can select either @strname or @strcode. But not both at a time.
In that case one like statement is ok but the alternative is always a burden over query because it will always be as
@STRNAME like '%%'
or as below
@STRCODE like '%%'
Now if I use this approach, will compiler cost some time to search like ‘%%’ even there is nothing to match or will it bypass it and cost nothing? I checked the execution plan also but it displays nothing for the like clause.
Hence I have to use this in webApps so speed of the sp has to consider. And the table has millions of rows.
Execution plan for both are same for both. If I use like cluase in query or remove it from query it shows – Clustred index sacn 100%.
Please help.
Firstly if either of the columns are nullable then testing
col LIKE '%%'is not a No-Op but is actually equivalent to testing that the columncol IS NOT NULLwhich may well not be the desired effect.Secondly if the column is not nullable so it truly is a No-Op then this is not a particularly good approach in that SQL Server will not optimise out the check. See Dynamic Search Conditions in T-SQL for better approaches.
Chances are in your case it won’t make much difference though.
As you are always doing a search with a leading wildcard against one or other column and you are doing
SELECT *then likely you will end up with a full table scan anyway.One case where it could make a difference would be where you have a narrower index on one or more of the columns that could be scanned in preference to scanning the whole clustered index / table. Even there however SQL Server would still need to do book mark lookups to retrieve the
*so could evaluate the residual predicate quite cheaply for that particular query.However the plan generated would be completely inappropriate for the invovcation with the other parameter so this attempt at a catch all query could give you a parameter sniffing issue as demonstrated below.
Test Table
Invoke first with name parameter (Scan count 1, logical reads 7)
Invoke with code parameter reusing same plan (Scan count 1, logical reads 7690)
Invoke with code parameter generate specific plan (Scan count 1, logical reads 2517)