Statement blocks in SQL SELECT using IF ELSE - sql

I'm trying to return different data depending on a variable in a SELECT. Something like this:
SELECT
IF #variable = 'YES'
column1, column2
ELSE
column3
FROM TABLE
What is this the proper way to use the IF condition in SQL? Or is there a better alternative to what I'm trying to accomplish?

If you want to return a different number of columns, you'll need to use an IF:
IF #variable = 'YES'
BEGIN
SELECT column1, column2
FROM YourTable
END
ELSE
BEGIN
SELECT column3
FROM YourTable
END
If you want different data on the same column (assuming the same datatype), you could use a CASE:
SELECT CASE WHEN #variable = 'YES' THEN column1 ELSE Column2 AS Data
FROM YourTable

You can use an IF statement, but you'll need to set up multiple queries. You can use a CASE for selecting one column or another, but not to select one or multiple like in your question.
DECLARE #var INT = 1;
DECLARE #test TABLE (
Col1 int,
Col2 int,
Col3 int
)
INSERT INTO #test VALUES (1,2,3)
IF #var = 1
BEGIN
SELECT Col1, Col2
FROM #test
END
ELSE
BEGIN
SELECT Col3
FROM #test
END

Related

Stored procedure setting a value if row is empty

How would I go about setting a value if a row is empty ('')?
I was thinking something like,
Got var with default value called #defaultValue to set it where the row in a table is ''.
if (select col1 from table1 where col1 = '')
set (select col1 from table1 where col1 = '') = #DefaultValue
is there a better way?
code is just a draft its not even tested..
If you want to update the table with #DefaultValue, you can use WHERE clause in the UPDATE query:
UPDATE table1
SET col1=#DefaultValue
WHERE col1=''
OR col1 IS NULL
OR
If you are trying to select #DefaultValue if the column is empty or null, you can do this:
SELECT CASE WHEN (col1 IS NULL OR col1='')
THEN #DefaultValue
ELSE col1
END AS Col1
FROM table1
select case when col1 ='' then #DefaultValues else col1 end from table
DEMO
declare #default int
set #default=1
declare #tbl table(col1 int)
insert into #tbl values(1),(''),(2)
select case when col1='' or col1 is null then #default else col1 end from #tbl

Sql server Query : Conditional Select columns with top keyword

DECLARE #mode INT;
SELECT CASE
WHEN #mode = 0
THEN t.Column1,Count(t.Column2) as Column2
ELSE top 1 t.Column1,Count(t.Column2) as Column2
END
FROM Table1 t
--Where some list of parameters
Group by t.Column1,t.Column2
Please read the above sql statement carefully. I have requirement to evaluate the query by two modes without changing the body of the query ie. From,Where and Group clauses should be written only once and not to replicate them (each one) anywhere in the result query
if #mode = 0 then the above said columns should be returned, and
if #mode <> 0 then the "Top1" of records should be returned
Both select conditions use the same given set list of parameters.
When I run the above query am facing the error "Incorrect syntax near the keyword 'top'." because we could not use the top 1 keyword within conditional select statements and select condition's columns must be matched even with their datatypes.
I need to fix the above query without affecting logic of the query.
IF(#mode <= 0)
BEGIN
Select Column1,Count(t.Column2) as Column2
From Table1 t
Group by t.Column1,t.Column2
END
Else
BEGIN
Select top 1 *
From Table1 t
END
Or create a temporary table and load data using where condition
Create Table #Temp (Column1 datetype,Column2 datetype)
Insert Into #Temp (Column1,Column2)
Select Column1,Column2
From Table1 t
Where condition
IF(#mode <= 0)
BEGIN
Select Column1,Count(t.Column2) as Column2
From #Temp t
Group by t.Column1,t.Column2
END
Else
BEGIN
Select top 1 *
From #Temp t
END
BEGIN
DECLARE #mode INT;
SET #mode = 0;
IF #mode <= 0
SELECT t.Column1,count(t.Column2) as Column2 from Table_Name t
GROUP BY t.Column1,t.Column2
ELSE
SELECT TOP 1 t.Column1,count(t.Column2) as Column2 from Table_Name t
GROUP BY t.Column1,t.Column2
END
DECLARE #mode INT;
Set #mode = 1 --for Min set of records
--Set #mode = 100 --for Max / full set of records
SELECT TOP (#var) PERCENT * t.Column1 ,Count(t.Column2) AS Column2 FROM Table1 t
--Where some list of parameters
GROUP BY t.Column1 ,t.Column2

Execute queries until non-empty result

I have three queries, looking like these:
SELECT * FROM Table1 WHERE Column1 = 'a'
SELECT * FROM Table2 WHERE Column2 = 'b'
SELECT * FROM Table1 A, Table2 B WHERE A.Column1 <> B.Column1
Now all logic is implemented on the client side as following. Execute the first query, if HasRows, set a flag to 1 and return the rows. Otherwise execute the second query, if HasRows, set the flag to 2 and return the rows. Otherwise execute the third query, set the flag to 3 and return the rows.
How to do this with a single query? Flag stuff, I guess, should be solved adding Flag to the queries:
SELECT Flag = 1, * FROM Table1 WHERE Column1 = 'a'
SELECT Flag = 2, * FROM Table2 WHERE Column2 = 'b'
SELECT Flag = 3, * FROM Table1 A, Table2 B WHERE A.Column1 <> B.Column1
But now what? How to check, if a query returns non-empty result?
Also, I'd like to cache the results, in other words, to avoid executing the same query twice - once for checking and the second time - for returning data.
Regards,
You could use a table variable to store the result and only return it at the end of the SQL block. Checking ##rowcount would tell you if the previous insert added any rows; if it's zero, you can run further queries:
declare #result table (flag int, col1 int, col2 varchar(50))
insert #result select 1, col1, col2 from Table1 where Column1 = 'a'
if ##rowcount = 0
begin
insert #result select 2, col1, col2 from Table2 where Column1 = 'b'
end
if ##rowcount = 0
begin
insert #result select 3, col1, col2 from Table1 A, Table2 B
where A.Column1 <> B.Column1
end
select * from #result
This approach only works if each select has the same column definition.

how to include the column name in case statement

I need to include a column name in the where clause of SQL query depending on a variable value.
For Example,
1. If I have a variable,say,#test and I assigned the variable with the value 1/0.
2. I have a table ,say, table1 with 2 column names col1,col2.
Now, I am writing a query to fetch some data from the table by including only one column at a time depends on the #test variable(declared earlier) i.e. I need to include col1 in the where clause of the query if the #test is 1 and col2 if #test is 0.
Please let me know the solution asap.
Thanks in advance
Select *
From dbo.MyTable
Where Case When #Test = 1 Then Col1 Else Col2 End > 100
declare #tbl table
(
col1 int,
col2 int
)
insert into #tbl select 10, 20
declare #test int
set #test = 1
select *
from #tbl
Where Case When #test = 1 Then Col1 Else Col2 End = 10
If datatype is different
select *
from #tbl
Where Case when #test = 1 Then Col1 end = 10
OR
Case when #test = 2 Then Col2 end = 'sometext'
A slightly different approach:
Select *
From dbo.MyTable
Where Col1 = Case When #Test = 1 Then 10 Else Col1 End and
Col2 = Case When #Test = 0 Then 'sometext' Else Col2 End
This version of the query may be sargable.

how to validate the input parameters before using in the static query?? SQL server 2005

consider table1 with 2 columns..
table1:
column1 int,
column2 char
create procedure SP1(#col1,#col2) as
begin
select * from table1 where _______
end
Question: User may enter valid input for either (col1 or col2) or (both col1 and col2).so i need to validate the user input and use those correct column(s) in the satic query.
eg: if both inputs are correct then, the query will be:
select * from table1 where column1=#col1 and column2 =#col2
if only col2 is valid and col1 is not a valida one, then this:
select * from table1 where column2=#col2
how to validate the input parameters before using in the static query?? in sql server 2005
You mean something like:
Create Procedure Sp1( #Col1..., #Col2... )
As
-- if #Col1 is not valid, then set it to Null
If #Col1 <> <valid number or string or date>
Set #Col1 = Null
-- if #Col2 is not valid, then set it to Null
If #Col2 <> <valid number or string or date>
Set #Col2 = Null
Select ...
From Table1
Where ( #Col1 Is Not Null Or #Col2 Is Not Null )
And ( Col1 = #Col1 Or #Col1 Is Null )
And ( Col2 = #Col2 Or #Col2 Is Null )
try this:
Create Procedure Sp1( #Col1..., #Col2... )
As
If #Col1 {is valid} AND #Col2 {is valid}
BEGIN
select * from dbo.table1 where column1=#col1 and column2 =#col2
END
ELSE #Col2 {is valid}
BEGIN
select * from dbo.table1 where column2=#col2
END
RETURN 0
GO
be careful using the (#col1 IS NULL or #Col1=Col1) trick, an index will not be used. Read Dynamic Search Conditions in T-SQL by Erland Sommarskog to see all the PROs and CONs of each dynamic search method. I chose the If method because the OP only lists 2 conditions to search on, so it would seem feasible to do it this way.
In such case it looks like dynamic SQL will be the best option - you will generate the WHERE clause depending on the validity of arguments and then execute the whole query with sp_executesql