I want to fetch the data based on the key_column in the table. I am having a procedure where i am passing the key character. If the key is 'A' only those records with key as 'A' should get selected . For any other key character other than 'A', I need all the records except the rows with the key_Column value 'A'
sample code:
select * from tab1
where
if (@key_Char = 'A') Then key_Column=@key_Char
ELSE key_Column <>@key_Char
IF… ELSE clause is very handy and whenever you need to perform any conditional operation, you can achieve your results using it. But there are some limitations in IF… ELSE, and one of the limitations is that you cannot use it in WHERE clause.
We can use SQL IF statement without ELSE as well. In the following, the expression evaluates to TRUE; therefore, it prints the message. If the expression evaluates to FALSE, it does not return any output. We should use ELSE statement so that if an evaluation is not TRUE, we can set default output.
IF condition in SQL IF() function is passed with two parameters, one for true and other for false. The function returns one value if a condition is TRUE, and another value if the condition is FALSE.
To sum up this tutorial, remember the simple rule: If you need to work with aggregate functions, use GROUP BY and HAVING. And if you need to apply general conditions, use WHERE.
You can try this
select * from tab1
where (@key_Char = 'A' AND key_Column='A') OR
(@key_Char <> 'A' AND key_Column <> 'A')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With