Is there an alternative way to create a stored procedure without putting the entire request in one long line if the criteria for the WWHERE clause can be different.
Suppose I have a table of orders. I want to create a stored procedure in this table, and there are three columns on which I will filter the records.
1- CustomerId, 2- SupplierId, 3- ProductId.
If the user provided CustomerId only in the search criteria, the request should look like this
SELECT * FROM Orders WHERE Orders.CustomerId = @customerId
And if the user only gives ProductId in the search criteria, then the query should look like this
SELECT * FROM Orders WHERE Orders.ProductId = @productId
And if the user is provided with only all three CustomerId, ProductId and SupplierId, then all three identifiers will be used in WHERE for filtering.
There is also a chance that the user will not want to filter the record, then the query should look like this:
SELCT * FROM Orders
Whenever I have to create such a procedure, I put all this in a string and use the IF conditions to check the argument values (@customeId or @supplierId, etc.).
I use the following method to create a procedure
DECLARE @query VARCHAR(MAX) DECLARE @queryWhere VARCHAR(MAX) SET @query = @query + 'SELECT * FROM Orders ' IF (@originationNumber IS NOT NULL) BEGIN BEGIN SET @queryWhere =@queryWhere + ' Orders.CustomerId = ' + CONVERT(VARCHAR(100),@customerId) END END IF(@queryWhere <> '') BEGIN SET @query = @query+' WHERE ' + @queryWhere END EXEC (@query)
Thanks.