October 25, 2011

Can we make where conditional in SQL Server?

I want to fetch records conditionally(where) how can i do that?
Conditions are If parameter is Null then all data other wise it will compare with parameter value.

image

Let's try to do this.

T-SQL
CREATE TABLE TableN
(ID INT,Val VARCHAR(50))
INSERT INTO TableN
SELECT 1,'X1' UNION ALL
SELECT 2,'X2' UNION ALL
SELECT 3,'X3' UNION ALL
SELECT 4,'X4' UNION ALL
SELECT 5,'X5' UNION ALL
SELECT 6,'X6' UNION ALL
SELECT 7,'X7' UNION ALL
SELECT 8,'X8'
DECLARE @Param VARCHAR(30)
SET @Param = 'X'
SELECT * FROM TableN 
WHERE 
1 = CASE WHEN @Param Is Null THEN 1 END   
OR
Val = @Param


That’s It
Enjoy Learning.

No comments:

Post a Comment