TSQL Case in where statement if parameter is null - sql

I have a SP that gives me a lot of hard times.
The sp gets a two parameters #madeByUserId and #reportedByUserId.
I want to have something like:
select * from table
where MadeByUserId = #madeByUserId (if(#reportedByUserID != null) and ReportedByUserID = #reportedByUserID)
Basically I want to make a case in the where clause to include another filter condition based of the null/not null state of the #reportedByUserId
Is that possible?
Thanks a lot,
Radu

Try:
select * from table
where MadeByUserId = #madeByUserId
AND (#reportedByUserID IS null OR ReportedByUserID = #reportedByUserID)

You could use COALESCE.
SELECT *
FROM Table
WHERE MadeByUserId = #madeByUserId
AND ReportedByUserID = COALESCE(#reportedByUserID, ReportedByUserID)
This translates to
if #reportedByUserID is `NOT NULL` then
compare ReportedByUserID with #reportedByUserID
else
compare ReportedByUserID with ReportedByUserID
From MSDN
COALESCE
Returns the first nonnull expression
among its arguments.

Add an if statement
IF (#reportedByUserId IS NOT NULL)
SELECT *
FROM table t
WHERE t.MadeByUserId = madeByUserId etc

I think this will give you what you're after.
IF (#reportedByUser IS NULL)
select * from table
where MadeByUserId = #madeByUserId
ELSE
select * from table
where MadeByUserId = #madeByUserId and ReportedByUserID = #reportedByUserID)

Related

Simulating an if condition in the WHERE clause of an SQL query

I am trying to write a google BigQuery to select some records based on this condition:
if ID_parameter is not null:
SELECT * WHERE ID=ID_parameter
else:
SELECT * WHERE country_id=country_id_parameter and (name LIKE %name_parameter% OR name is null)
The name_parameter should be optional but one of the ID_parameter or country_id_parameter must be provided.
Sorry, I am a newbie with SQL but I hope I stated what I want clearly.
consider below approach
select *
from your_table
where case
when not id_parameter is null then id = id_parameter
else country_id = country_id_parameter and (regexp_contains(name, name_parameter) or name is null)
end
I miss the table name in the query, let's assume it's 'personnel'.
Suppose ID-parameter = 200, country_id_parameter = 'NL', name_parameter = '%bart%'
Maybe like this when the name is 'bart':
select * from personnel
where ID=200
or (ID=NULL and
country_id='NL' and
name LIKE '%bart%')
Use this when the name is NULL:
select * from personnel
where ID=200
or (ID=NULL and
country_id='NL')

change where condition based on column value

I faced the following requirement. The following query is called by a procedure. The value p_pac_code is the input parameter of the procedure.
The requirement is the query should have an additional condition sp_sbsp.SUBSPCLTY_CODE!='C430 if the p_pac_code value is '008'.
For any other p_pac_code value, it should run as it is below. Is there way to do this by adding an additional condition in the WHERE clause?
As for now, I have done this using IF.....ELSE using the query two times separately depending on p_pac_code value. But I am required to find a way to do with just adding a condition to this single query.
SELECT ptg.group_cid
FROM PRVDR_TYPE_X_SPCLTY_SUBSPCLTY ptxss,
PT_X_SP_SSP_STATUS pxsst ,
pt_sp_ssp_x_group ptg,
group_x_group_store gg,
specialty_subspecialty sp_sbsp,
treatment_type tt,
provider_type pt
WHERE
pt.PRVDR_TYPE_CODE = ptxss.PRVDR_TYPE_CODE
AND tt.TRTMNT_TYPE_CODE = pxsst.TRTMNT_TYPE_CODE
AND ptxss.PRVDR_TYPE_X_SPCLTY_SID = pxsst.PRVDR_TYPE_X_SPCLTY_SID
AND tt.TRTMNT_TYPE_CODE = p_pac_code
AND TRUNC(SYSDATE) BETWEEN TRUNC(PXSST.FROM_DATE) AND TRUNC(PXSST.TO_DATE)
AND ptg.prvdr_type_code =ptxss.prvdr_type_code
AND ptg.spclty_subspclty_sid = ptxss.spclty_subspclty_sid
AND ptxss.spclty_subspclty_sid = sp_sbsp.spclty_subspclty_sid
AND ptg.spclty_subspclty_sid = sp_sbsp.spclty_subspclty_sid
AND ptg.status_cid = 2
AND ptg.group_cid = gg.group_cid
AND gg.group_store_cid = 16
AND gg.status_cid = 2;
Thanks in advance.
You can simply add a condition like this:
... and (
( sp_sbsp.SUBSPCLTY_CODE!='C430' and p_pac_code = '008')
OR
NVL(p_pac_code, '-') != '008'
)
This can be re-written in different ways, this one is quite self-explanatory
Just add:
AND NOT ( NVL( sp_sbsp.SUBSPCLTY_CODE, 'x' ) = 'C430'
AND NVL( p_pac_code value, 'x' ) = '008' )
to the where clause.
The NVL function is used so that it will match NULL values (if they exist in your data); otherwise, even though NULL does not match C430 you will still find that NULL = 'C430' and NULL <> 'C430' and NOT( NULL = 'C430' ) will all return false.
Quite easy. Add the following condition:
AND (sp_sbsp.SUBSPCLTY_CODE != 'C430' OR p_pac_code value != '008')
(don't forget the parenthesis)
Just sharing
SELECT ptg.group_cid
FROM PRVDR_TYPE_X_SPCLTY_SUBSPCLTY ptxss
WHERE
pt.PRVDR_TYPE_CODE = ptxss.PRVDR_TYPE_CODE
&&((tt.TRTMNT_TYPE_CODE = pxsst.TRTMNT_TYPE_CODE)
or (tt.TRTMNT_TYPE_CODE = pxsst.TRTMNT_TYPE_CODE))
just use the parenthesis to specify where the conditionmust implement.

Use CASE statement to test values in table 1, set values in table 2

I am new to SQL, so if you could include in answer correct syntax (for PostgreSQL) that will be great.
I have two tables
table 1 "geo_temp", with columns [geo_type1] [geo_type2]....[geo_type6] [geo_typeR];
table 2 "geo_summary", with column [geo].
Here what I want to do,
CASE
WHEN (geo_type1 NOTNULL) THEN (geo = geo_type1)
WHEN (geo_type2 NOTNULL) THEN (geo = geo_type2)
...
ELSE (geo = geo_typeR)
Your help is much appreciated. Thanks.
Use the coalesce() function:
geo = coalesce(geo1, geo2, ...,geoR)
coalesce() returns the first non-null value found in the list, which is what your intention is.
As an update statement:
update geo_summary set
geo = (select coalesce(geo1, geo2, ...,geoR)
from geo_temp
where geo_temp.id = geo_summary.id)
I am assuming you want to use this in a WHERE or ON Clause.
You could do something like...
geo =
CASE
WHEN (geo_type1 is NOT NULL) THEN geo_type1
WHEN (geo_type2 is NOT NULL) THEN geo_type2
...
ELSE geo_typeR
END

Where clause in sql

My sql query is as follows
IF #StatusId = 10
BEGIN
SELECT
*
FROM
Risk AS R
INNER JOIN Statuses AS St ON R.Status_Id=St.Status_Id
WHERE
R.MitigationOwner = COALESCE(#MitigationOwner,R.MitigationOwner)
AND R.RiskFactor = COALESCE(#RiskFactor,R.RiskFactor)
AND R.RiskArea = COALESCE(#RiskArea,R.RiskArea)
AND R.AddedWhen BETWEEN
COALESCE(CONVERT(DATETIME, #StartDate+'00:00:00',120),R.AddedWhen) AND
COALESCE(CONVERT(DATETIME,#EndDate+'23:59:59',120),R.AddedWhen)
END
When I pass only status Id and all other variables are null, then records with NULL MitigationOwner or ModifiedDate are not displayed..
What is wrong in this query?
Use the form:
...
(R.MitigationOwner = #MitigationOwner OR #MitigationOwner IS NULL)
...
This is optimised in SQL Server. COALESCE isn't.
Edit: This does the same as Paul Williams' answer but his answer allows explicit "NULL = NULL" matches. m ylogic is simpler because NULL never equals NULL.
I believe that by ModifiedDate you meant R.AddedWhen
try this:
SELECT
*
FROM
Risk AS R
INNER JOIN Statuses AS St ON R.Status_Id=St.Status_Id
WHERE
(R.MitigationOwner = COALESCE(#MitigationOwner,R.MitigationOwner) OR R.MitigationOwner IS NULL)
AND R.RiskFactor = COALESCE(#RiskFactor,R.RiskFactor)
AND R.RiskArea = COALESCE(#RiskArea,R.RiskArea)
AND (R.AddedWhen BETWEEN
COALESCE(CONVERT(DATETIME, #StartDate+'00:00:00',120),R.AddedWhen) AND
COALESCE(CONVERT(DATETIME,#EndDate+'23:59:59',120),R.AddedWhen) OR R.AddedWhen IS NULL)
If R.MitigationOwner can be null, then your comparison clause:
WHERE
R.MitigationOwner = COALESCE(#MitigationOwner,R.MitigationOwner)
Must be rewritten to handle NULL values:
WHERE
((R.MitigationOwner IS NULL AND #MitigationOwner IS NULL)
OR (R.MitigationOwner = #MitigationOwner))
See this article on Wikipedia about NULL.

sql select with one value of two where

This is the only place that I get all answer ;)
I want to select :
SELECT
RTRIM(LTRIM(il.Num_bloc)) AS Bloc,
RTRIM(LTRIM(il.num_colis)) AS Colis,
cd.transporteur AS Coursier,
cd.origine AS Origine,
cd.destination AS Destinataire,
cd.adresse AS [Adresse Destinataire],
cd.poids AS Poids,
il.Signataire, il.num_cin AS CIN, il.date_livraison AS [Date Livraison]
FROM
dbo.cd
INNER JOIN
dbo.il ON cd.bloc = il.Num_bloc AND dbo.cd.colis = dbo.il.num_colis
WHERE
(il.Num_bloc = RTRIM(LTRIM(#ParamBloc)))
AND (il.num_colis = RTRIM(LTRIM(#ParamColis)))
In the way of getting result if the user put ether #ParamBloc or #ParamColis
Try using IsNull() function.
A simple query would go like this
Select * from yourTable
Where
Num_bloc = ISNULL(#ParamBloc, Num_block) AND
num_colis = ISNULL(#ParamColis, num_colis)
The second parameter would make the expression to true if the #parameter Bloc or Colis is null. This query would be useful for all 4 possible combination of these two parameter.