Dynamic search without dynamic SQL

The user can search for a client by the first, last and, possibly, when entering the city.

Is it possible to write SQL that matches CITY only if the user entered one without using dynamic SQL?

CREATE PROCEDURE [dbo].[SearchCustomer] @FirstName varchar(30) --REQUIRED @LastName varchar(30)--REQUIRED @City varchar(30) --OPTIONAL AS SELECT * FROM CUSTOMER C WHERE C.FirstName = @FirstName AND C.LastName = @LastName AND C.City = IsNull(@City, C.City) --This won't Work if CITY is optional in the database 
+4
source share
3 answers

Try:

 (@City is null OR C.City = @City) 
+6
source

try it

 COALESCE(C.City,"") = COALESCE(@City,C.City,"") 

Read more about this feature here.

+2
source
 CREATE PROCEDURE [dbo].[SearchCustomer] @FirstName varchar(30) --REQUIRED @LastName varchar(30)--REQUIRED @City varchar(30) --OPTIONAL AS IF @City is NULL BEGIN SELECT * FROM CUSTOMER C WHERE C.FirstName = @FirstName AND C.LastName = @LastName END ELSE BEGIN SELECT * FROM CUSTOMER C WHERE C.FirstName = @FirstName AND C.LastName = @LastName AND C.City = @City END 
0
source

Source: https://habr.com/ru/post/1342805/


All Articles