IF ELSE in where block of sql query - sql

I have the below stored procedure
CREATE PROCEDURE sp1
(
#param1 bit,
#parma2 bit
)
AS
BEGIN
SELECT * from Table1 where
if #param1 = 1 then column1 is null
else if #parma2 = 1 then column1 is not null
END
Obviously the If else part in the where clause is not correct . Could anyone suggest how to tackle it ?

Something like this:
SELECT * from Table1 where
case
when #param1 = 1 then [column 1] is null
when #param2 = 1 then [column 1] is not null
end
But you don't need two parameters for this procedure, only one should suffice.

Try the following:
SELECT
Case WHEN #param1 = 1 THEN Null
Case WHEN #param2 = 1 THEN column1 Else '' End as column1 ,
* FROM Table1
The above statement will set column1 to null if param1 = 1, it will get the value of column1 if param2 = 1 otherwise it will set it to empty string.

Seems to me like the simplest option would be to use AND and OR:
SELECT *
FROM Table1
WHERE (#param1 = 1 AND column1 is null)
OR (#parma2 = 1 AND column1 is not null)

Use this:
CASE WHEN condition THEN value ELSE value END

Related

Select default if no rows return

SELECT Column1
FROM Table1
WHERE PKColumn = SomeValue
I am selecting just one column, my query will return only 0 or 1 row for sure. I want to select some default values like Some Default if no row returned otherwise the returned value.
I tried something like
SELECT CASE WHEN COUNT(1) = 1 THEN Column1 ELSE 'Some Default' END AS Column1
FROM Table1
WHERE PKColumn = SomeValue
GROUP BY Column1
But it doesn't work.
Is there any way to do it in single SQL statement?
I think you can use a query like this:
SELECT TOP(1)
CASE WHEN EXISTS(SELECT 1 FROM t WHERE PKColumn = SomeValue) THEN Column1
ELSE 'Some Default' END AS Column1
FROM t;
Or using EXISTS with UNION:
SELECT 'Some Default' As Column1
WHERE NOT EXISTS(SELECT 1 FROM t WHERE PKColumn = SomeValue)
UNION ALL
SELECT Column1
FROM t
WHERE PKColumn = SomeValue;
You can use COALESCE
Evaluates the arguments in order and returns the current value of the
first expression that initially does not evaluate to NULL.
SELECT COALESCE((SELECT TOP 1 Column1 FROM Table1 WHERE PK = SomeValue), 'DefaultValue')
or like this:
DECLARE #ReturnValue INT = 3 -- Default value
SELECT TOP 1 #ReturnValue = Column1 FROM Table1 WHERE PK = SomeValue
SELECT #ReturnValue
SELECT
[Column1] = ISNULL([t2].[Column1], 'Some Default')
FROM
[Table1] AS [t1]
OUTER APPLY
(
SELECT
[Column1]
FROM
[Table1]
WHERE
[PKColumn] = [t1].[PKColumn]
) AS [t2]
WHERE
[t1].[PKColumn] = 'SomeValue';
Perhaps can try using LEN instead of COUNT to check if Column1 has value?
SELECT CASE WHEN LEN(Column1) > 0 THEN Column1 ELSE 'Some Default' END AS Column1
FROM Table1
WHERE PKColumn = SomeValue
GROUP BY Column1

Where Case - why does this not return what its supposed to

The following fragment of a stored procedure:
#column1 varchar(50)
#column2 bit
SELECT column1 ,column2
FROM table1
WHERE column1 = case when #column1 = '' then column1 else #column1 end
and column2 = case when #column2 = 0 then column2 else 1 end
does not return anything.
When I remove this line:
and column2 = case when #column2 = 0 then column2 else 1 end
it works as expected, as it should if #column2 = 0.
Is there a different/better way to do this?
A simpler, more readable and more reliable way is to only check the value if it needs checking:
WHERE (#column1 = '' OR column1 = #column1)
AND (#column2 = 0 OR column2 = #column2)
Or (probably) better, pass NULLs for your variables when you don't require a particular value:
WHERE (#column1 IS NULL OR column1 = #column1)
AND (#column2 IS NULL OR column2 = #column2)
Using NULLs also allows column1 to require a blank and column2 to require a 0, values which is not possible when you reserve those values to mean "don't care" (this issue applies to whatever approach you eventually use)
Use (NULL OR Value) AND (NULL OR Value)
#column1 varchar(50)
#column2 bit
SELECT column1
,column2
FROM table1
WHERE
((#column1 IS NULL OR #Column1='') OR column1 = #column1)
and
((#column2 IS NULL) OR column2 = #column2)
You run into problems with NULL since NULL=NULL is not true.
Use conditions like this instead, which are also easier on the query optimizer:
WHERE ((#column1 = '') OR (column1 = #column1))
Hint: If you have this in a stored procedure, it may be a good idea to add an OPTION (RECOMPILE) at the end of the statement in order to have the query optimizer re-run while taking the # variables into account as constants.
Since there were only null values in the database right now, all that was needed was ISNULL(column2, 0) = case when #column2 = 0 then column2 else 1 end

Get row from table based on parameter

I want to get row from based on parameter value. Either it could be value 'ABC' or NULL. Below is the source table and expected result, which I'm trying to achieve.
SourceTable
column1 column2
--------------------------
value1 NULL
value2 ABC
Tried with query, but it is getting two rows which are with value1 and value2.
Declare #Param1 varchar(20) = 'ABC'
Select *
from SourceTable
where column2 = #Param1 Or column2 is NULL
If value is 'ABC' then Result -
column1 column2
--------------------------
value2 ABC
If value is NULL then Result -
column1 column2
--------------------------
value1 NULL
Perhaps this would work for you?
select *
from SourceTable
where column2 = #Param1 or (#Param1 is null and column2 is null)
You can try something like: Only problem you might encounter with this is if your column2 has blanks.
SELECT *
FROM SourceTable
WHERE ISNULL(column2, '') = ISNULL(#Param1, '')
Perhaps you want union all and a check for existence:
Select *
from SourceTable
where column2 = #Param1
union all
Select *
from SourceTable
where column2 is null and not exists (select 1 from sourcetable st2 where st2.column2 = #Param1);
An alternative uses order by -- if you want only one row:
select top 1 st.*
from sourcetable st
where column2 = #param1 or column2 is null
order by (case when column2 is not null then 1 else 2 end);

case statement in where clause depending on variable value

Depending on variable value my Where condition should change
If #CustID <> 0 Then
Where SomeColumn = #BillID
Else
Where SomeColumn In (#BillID,0)
My Query:
Select *
From SomeTable
Where SomeColumn = (Case When #CustID <> 0 Then #BillID Else /* What to Write Here */ End)
Here is the query you're looking for:
SELECT *
FROM SomeTable ST
WHERE (#CustID <> 0 AND ST.SomeColumn = #BillID)
OR (#CustID = 0 AND ST.SomeColumn IN (#BillID, 0))
Hope this will help.

How do I create a conditional WHERE clause?

I need to have a conditional where clause that operates as so:
Select *
From Table
If (#booleanResult)
Begin
Where Column1 = 'value1'
End
Else
Begin
Where column1 = 'value1' and column2 = 'value2'
End
Any help would be appreciated.
Could you just do the following?
SELECT
*
FROM
Table
WHERE
(#booleanResult = 1
AND Column1 = 'value1')
OR
(#booleanResult = 0
AND Column1 = 'value1'
AND Column2 = 'value2')
You can group conditions easily in a WHERE clause:
WHERE
(#BooleanResult=1 AND Column1 = 'value1')
OR
(#BooleanResult=0 AND Column1 = 'value1' AND column2 = 'value2')
Based on the script in question, it seems that you need the condition for Column1 irrespective of whether the variable #booleanResult is set to true or false. So, I have added that condition to the WHERE clause and in the remaining condition checks whether the variable is set to 1 (true) or if it is set to 0 (false) then it will also check for the condition on Column2.
This is just one more way of achieving this.
Create and insert script:
CREATE TABLE MyTable
(
Column1 VARCHAR(20) NOT NULL
, Column2 VARCHAR(20) NOT NULL
);
INSERT INTO MyTable (Column1, Column2) VALUES
('value1', ''),
('', 'value2'),
('value1', 'value2');
Script when bit variable is set to 1 (true):
DECLARE #booleanResult BIT
SET #booleanResult = 1
SELECT *
FROM MyTable
WHERE Column1 = 'value1'
AND ( #booleanResult = 1
OR (#booleanResult = 0 AND Column2 = 'value2')
);
Output:
COLUMN1 COLUMN2
------- -------
value1
value1 value2
Script when bit variable is set to 0 (false):
DECLARE #booleanResult BIT
SET #booleanResult = 0
SELECT *
FROM MyTable
WHERE Column1 = 'value1'
AND ( #booleanResult = 1
OR (#booleanResult = 0 AND Column2 = 'value2')
);
Output:
COLUMN1 COLUMN2
------- -------
value1 value2
Demo:
Click here to view the demo in SQL Fiddle.
To provide a shorter answer:
Select *
From Table
Where Column1 = 'value1' and
coalesce(column2, '') = (case when #BooleanResults = 0
then 'value1'
else coalesce( column2, '')
end)
Query 1: if the #CompanyID is set to -1 then all records are selected
Query 2: if the #CompanyID is set to 10 or 11 or 12, only those records are selected where the companyid=#CompanyID
Declare #CompanyID int
Set #CompanyID = -1
select * from sales
where 1=IIF(#CompanyID =-1, 1, IIF(CompanyID =#CompanyID,1,0))
Set #CompanyID = 10
select * from sales
where 1=IIF(#CompanyID =-1, 1, IIF(CompanyID =#CompanyID,1,0))