Hi everyone,
I have a table: T1
Col1 Col2
NULL 1
son 1
sun 3
NULL 4
su 5
And a stored Procedure with a query that queries that above table.
----- Stored Proc ----
Create procedure (@param1, @param2)
...
query
...
GO
---- End of Stored Proc ----
I need to write a query, as part of a Stored Procedure, to be able to accept NULL values as parameter (for col1) and still be able to return matching records.
Example: If I give @param1 = NULL and @param2 = 1 I want to get the first and second rows. But if @param1 = 'son' and @param2 = 1, I want the results to be only First record.
Query:
Version 1
select *
from T1
where col1 = COALECSE(@param1, col1)
and col2 = COALESCE(@param2, col2)
Comments:
For this, if I send parameters as @param1 = NULL, @param2 = 1. I don't get any records. Cuz' col1 has null value]
Version 2
check which parameters do not have nulls and accordingly build a SQL query. Then run it using EXEC()
Comments:
If there 10 parameters, this might get ugly
There must be a better way to do this....
Please suggest,
_ub
I have a table: T1
Col1 Col2
NULL 1
son 1
sun 3
NULL 4
su 5
And a stored Procedure with a query that queries that above table.
----- Stored Proc ----
Create procedure (@param1, @param2)
...
query
...
GO
---- End of Stored Proc ----
I need to write a query, as part of a Stored Procedure, to be able to accept NULL values as parameter (for col1) and still be able to return matching records.
Example: If I give @param1 = NULL and @param2 = 1 I want to get the first and second rows. But if @param1 = 'son' and @param2 = 1, I want the results to be only First record.
Query:
Version 1
select *
from T1
where col1 = COALECSE(@param1, col1)
and col2 = COALESCE(@param2, col2)
Comments:
For this, if I send parameters as @param1 = NULL, @param2 = 1. I don't get any records. Cuz' col1 has null value]
Version 2
check which parameters do not have nulls and accordingly build a SQL query. Then run it using EXEC()
Comments:
If there 10 parameters, this might get ugly
There must be a better way to do this....
Please suggest,
_ub