I have to write one Stored Procedure, In which I have to find the value from the table on the basis of Last Name, Last name search criteria can be Exact, Begin with or Phonetic.
SP will be like –
SELECT * FROM Person
WHERE (
CASE @lastNameCriteria
WHEN 'EXACT' THEN Person.LastName = @LastName
WHEN 'BEGIN' THEN Person.LastName like @LastName
ELSE SOUNDEX(tblPerson.LastName) LIKE SOUNDEX(@lastName))
I dont know above query will give in SQL. I dont want to use dynamic query, I can not use “IF ELSE”, because there might be some other criteria like FirstNameCriteria, MiddleNameCriteria, which will increase the complexity of “IF ELSE”.
Please suggest me what to do.
You can use the CASE statement properly like this
Which will force SQL Server to evaluate the @lastNameCriteria before processing the embedded conditions. You can also use multiple OR clauses which by virtue of @lastNameCriteria being compared to a string literal will cause
short-circuitboolean evaluation – the parts involving the column comparison is not evaluated unless the @lastNameCriteria matches).Notes:
=that you are after@lastNameCriteriawhich is why it is tested for both nulls and not in the other twooption (recompile)bit. Planning (each time) for such a simple query should take insignificant time.