Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand IF statements in sql

Tags:

sql

sql-server

Currently I have a stored proc, which takes a string

@vari as varchar(30)
if @vari is null 
    SELECT * FROM TABLE 
else 
    SELECT * FROM TABLE WHERE col = @vari
endif

is there any way to inline the if statement, thereby not declaring 2 select's just because of 1 param?

like image 241
Alex Avatar asked May 11 '12 13:05

Alex


People also ask

Which is better IIF or CASE?

For small items with two outcomes, I typically use IIF statements (i.e. If x < a, then 1, else 0) but for longer drawn out statements that can have multiple outcomes, I use CASE.

Which is faster case or IIF?

The CASE is slightly faster than IIF. IF is a control of flow statement; it indicates which T-SQL statement to evaluate next, based on a condition. CASE is a function -- it simply returns a value.

Is != And <> the same in SQL?

If != and <> both are the same, which one should be used in SQL queries? Here is the answer – You can use either != or <> both in your queries as both technically same but I prefer to use <> as that is SQL-92 standard.


1 Answers

SELECT * FROM TABLE WHERE (@vari is null or col = @vari)
like image 165
Nikola Markovinović Avatar answered Oct 12 '22 14:10

Nikola Markovinović