SQL Case When within where clause based on an Parameter input - where-clause

I'm currently in the middle of creating a report witch is parameter based and want to use a case when statement within my where clause.
Declare #TPS Varchar(152) = 'Include'
And (CASE WHEN #TPS = 'Include' THEN (TPS is null or (TPS = '')) ELSE (TPS IS NOT NULL) END)
above is the sample of what i'm trying to do. I cannot use a begin and end as i want to have 7 case whens within my statement so the user in SSRS can pass the values through into the report and that will be a lot of combinations.
I want to be able to pass through a parameter and in turn change my where clause.

You can have a case statement, or a series of case statements, in a where clause:
Declare #TPS Varchar(152) = 'Include'
select * from someTable
WHERE CAT = 'Spot' AND
CASE
WHEN #TPS = 'Include' then true
WHEN #TPS = null or #TPS = '' then false
WHEN #TPS not = null then true
else false
END
Just think of the case statement as returning a true or false

Related

SQL CASE that matches value or uses LIKE '%'

I'm trying to do a wildcard retrieve if a defined variable is blank. But I can't figure out the correct syntax.
SELECT ...
FROM ...
WHERE customers = CASE
WHEN ISNULL(#customerID, '') = '' THEN LIKE '%'
ELSE #customerID
END
It is as simple as this:
WHERE customers = NULLIF(#customerID, '') OR NULLIF(#customerID, '') IS NULL
The expression NULLIF(x, '') will convert '' to null. Then we take advantage of how null comparison works:
If #customerID is not null then first condition will be true only for exact match
If #customerID is null then first condition will be false (nothing equals null) but second condition will be true for all rows
DB<>Fiddle
You can just simply put it like this
SELECT...
FROM...
WHERE customers = ISNULL(#customerID,'') OR (ISNULL(#customerID,'') = '')
This should work because if the first condition was met, it will select the specific customer id. Otherwise, if the customer id is null,it will select all data because of this condition below:
(ISNULL(#customerID,'') = ''
If NULL, '' = '' will be true.

SSRS - Empty value

I have a parameter #Destinataire in SSRS that has a list of values plus an empty string
I've created a query that I set as available values, which gives me the drop down list
SELECT code_name FROM tableA UNION ALL SELECT ''
When running the reports with the empty string, I have no results
I tried to set the parameter as text box and it does not do anything too
Yet when running the sql query I'm using to run this report, things are fine as I have all my rows retrieved (see query below)
DECLARE #DateCmt DATE = '05/09/2015',
#DateFin DATE = '05/09/2016',
#Restriction INT = 1,
#Destinataire VARCHAR(5) = ''
--
;
--SELECT #DateCmt,#DateFin
SELECT DISTINCT
CFE_EDI.IU_LIASSE
,CFE_EDI.ETAT
,CFE_EDI.DATHRMAJ -- nouveau
,CFE_EDI.ESP_APPLI
,CFE_EDI.NOM_RS
,PARTENAIRES.LIBEL
,PARTENAIRES.CODE_INSEE
,CFE_EDI.DATHR_ENV -- nouveau
,CFE_EDI.DATHR_MEF -- nouveau
,CFE_EDI.DATHR_PRE -- nouveau
,CFE_EDI.DATHR_OUV -- nouveau
--,CFE_EDI.DATEHR_DEPOT-- mettre l'heure
,CFE_EDI.GESTDEL
--,CFE_SERVICE_DEST.IU_DEST
--,CFE_SERVICE.IU_LIASSE
,CASE WHEN CFE_EDI.ETAT = 'MEF' THEN 'En Attente le'
WHEN CFE_EDI.ETAT = 'PRE' THEN 'Préparé le'
WHEN CFE_EDI.ETAT = 'ENV' THEN 'Envoyé le'
WHEN CFE_EDI.ETAT = 'OUV' THEN 'Réceptionné le'
WHEN CFE_EDI.ETAT = 'NRM' THEN 'Non remis le'
WHEN CFE_EDI.ETAT = 'NAQ' THEN 'Non acquitté le'
END AS ChampEtat
,CASE WHEN CFE_EDI.ETAT = 'OUV' THEN 'Date d''envoi : ' + CONVERT(VARCHAR,CFE_EDI.DATHR_ENV,103)
END AS Date_Envoi,
CASE
WHEN CFE_EDI.ETAT='MEF' THEN CONVERT(VARCHAR,CFE_EDI.DATHR_MEF,103)
WHEN CFE_EDI.ETAT='PRE' THEN CONVERT(VARCHAR,CFE_EDI.DATHR_PRE,103)
WHEN CFE_EDI.ETAT='ENV' THEN CONVERT(VARCHAR,CFE_EDI.DATHR_ENV,103)
WHEN CFE_EDI.ETAT='OUV' THEN CONVERT(VARCHAR,CFE_EDI.DATHR_OUV,103)
ELSE CONVERT(VARCHAR,CFE_EDI.DATHR_DEPOT,103) END AS DateMaj ,
CASE
WHEN CFE_EDI.ETAT='MEF' then CONVERT(VARCHAR,CFE_EDI.DATHR_MEF,108)
WHEN CFE_EDI.ETAT='PRE' then CONVERT(VARCHAR,CFE_EDI.DATHR_PRE,108)
WHEN CFE_EDI.ETAT='ENV' then CONVERT(VARCHAR,CFE_EDI.DATHR_ENV,108)
WHEN CFE_EDI.ETAT='OUV' then CONVERT(VARCHAR,CFE_EDI.DATHR_OUV,108)
ELSE CONVERT(VARCHAR,CFE_EDI.DATHR_DEPOT,108) END AS HeureMaj,
PARTENAIRES.LIBEL + '(' + CFE_EDI.CODE_INSEE + ')' AS LibelDestinataire
--,CASE WHEN #Restriction = 1 THEN '1'
-- WHEN #Restriction = 0 THEN '0' END AS Restriction
,CASE WHEN #DateCmt != #DateFin AND #DateCmt < #DateFin THEN 'Diffusion Xml du ' + CONVERT(VARCHAR,(#DateCmt),103) + ' au ' + CONVERT(VARCHAR,(#DateFin),103) ELSE
'Diffusion EDI Xml du ' + CONVERT(VARCHAR,#DateCmt,103) END AS Plage_Diffusion
-- INTO
FROM
(PARTENAIRES
INNER JOIN dbo.CFE_EDI ON PARTENAIRES.CODE_INSEE = CFE_EDI.CODE_INSEE)
INNER JOIN dbo.CFE_SERVICE ON CFE_EDI.IU_LIASSE = CFE_SERVICE.IU_LIASSE
INNER JOIN dbo.CFE_SERVICE_DEST ON (PARTENAIRES.IU_PART = CFE_SERVICE_DEST.IU_PART_CFE)
WHERE
case when #Restriction = 1
then case when CFE_EDI.ETAT in('ENV','OUV') then 1 else 0 end
when #Restriction = 0
then case when CFE_EDI.ETAT not in('ENV','OUV') then 1 else 0 end
else case when CFE_EDI.ETAT <> '' then 1 else 0 end
end = 1
AND
CFE_EDI.CODE_INSEE IS NOT NULL AND CFE_EDI.CODE_INSEE != ''
AND CASE --WHEN CFE_EDI.CODE_INSEE IS NOT NULL AND CFE_EDI.CODE_INSEE !=''
--THEN CASE
WHEN #Destinataire != '' AND (#Destinataire) IS NOT NULL
THEN CASE WHEN CFE_EDI.CODE_INSEE = #Destinataire THEN 1 ELSE 0 END
ELSE CASE WHEN CFE_EDI.CODE_INSEE = PARTENAIRES.CODE_INSEE
AND cfe_edi.dathrmaj > #DateCmt AND cfe_edi.dathrmaj < #DateFin
AND CFE_EDI.GESTDEL = '1' THEN 1 ELSE 0 END
END = 1
First question would be to know if there is way to setup the parameter without using my stupid trick.
Second question is why the query with parameter with an empty string does the trick and once you use SSRS, nothing.
Thanks in advance for your help
Update I tried to set the WHEN LEN(#Destinataire) > 0 with the #Destinataire = '' but no luck on that one.
Update 2 My aim now is to have a solution that will retrieve all the datas, in case the #Destinataire is equal to '' or NULL. However, thinking about it, this solution is equivalent to having all the values populated in #Destinataire. So one way or another, I would say.
Final update I've recreated everything from scratch and oh! magic, the grouping or the everything option worked as wish. I still don't know what was wrong but I'm fine with the results. Many thanks for your help and support.
looking at your query and where you pass #Destinataire you should be able to pass a null value according to the where clause and get the same effect as passing ''
CASE --WHEN CFE_EDI.CODE_INSEE IS NOT NULL AND CFE_EDI.CODE_INSEE !=''
--THEN CASE
WHEN #Destinataire != '' AND (#Destinataire) IS NOT NULL
THEN CASE WHEN CFE_EDI.CODE_INSEE = #Destinataire THEN 1 ELSE 0 END
ELSE CASE WHEN CFE_EDI.CODE_INSEE = PARTENAIRES.CODE_INSEE
AND cfe_edi.dathrmaj > #DateCmt AND cfe_edi.dathrmaj < #DateFin
AND CFE_EDI.GESTDEL = '1' THEN 1 ELSE 0 END
END = 1
I would try to just set that particular paramter to allow nulls in the ssrs report which can be found as a checkbox in your parameter settings window.
There is a hybrid option, where you can keep your visible parameter just as you have it, but then use a hidden cascaded parameter to reference in the query. So if you really are having trouble with formulating your query with blank or null values as a parameter, this will work around that. Here are the steps:
Create a new dataset.
A slight catch, you do need to make sure that the changing the selection always adds a new value to force a refresh of the cascaded parameter, but that's easy to do:
SELECT code_name FROM tableA WHERE #Destinataire='' OR #Destinataire=code_name
--Dummy value needed to force update of parameter value in some cases:
UNION SELECT 'zz' + #Destinataire AS code_name
Set up a new parameter, #MultiDestataire. Allow it to accept multiple values and use the new dataset as its available and default values. Set its visibility to Hidden.
Running the report before hiding the new parameter shows how it works:
Edit the query to use the new multivalue parameter in its WHERE clause.
From here on, this is just altering the query to use the IN statement, which should look like this:
CFE_EDI.CODE_INSEE IS NOT NULL AND CFE_EDI.CODE_INSEE != ''
AND CFE_EDI.CODE_INSEE IN (#MultiDestinataire)
...
Attempting this may end up being an intermediary step if you've got some other issue in the query that's responsible for unexpected results, as you should be able to test for an empty value there.
This is just my two cents, basically you have two options here.
Multivalue parameter Option
Define your parameter to allow multivalues, use the same dataset in Available values and Default values properties. So when your user doesn't select any value the parameter will be populated with all values. Otherwise your parameter will be populated only with values your users select.
In this case you will have to use IN operator since your parameter represent multiple values seleted or not by your user.
...
WHERE CFE_EDI.CODE_INSEE IN (#Destinataire)
...
When you use Default values property all drop down list values are selected by default and your report run without any filter being applied (at least if your user doesn't select any value or values).
Additional, I'd avoid use '' (blank), it is uninformative and your user might think it is some kind of error or your parameter was not populated properly.
Why use a single value parameters when you want to show data from more than one value (in your case all)?
Single value Option (No sense IMO)
In order to this works you have to set your parameter to Allow blank value ("") and Allow null value. Your query should look like this:
WHERE
CASE WHEN #Destinataire = '' OR #Destinataire is null THEN 1 ELSE 0 END = 1
OR
CFE_EDI.CODE_INSEE = #Destinataire
In your query I think it could be something like this:
WHERE CASE
WHEN #Restriction = 1 THEN
CASE
WHEN cfe_edi.etat IN( 'ENV', 'OUV' ) THEN 1
ELSE 0
END
WHEN #Restriction = 0 THEN
CASE
WHEN cfe_edi.etat NOT IN( 'ENV', 'OUV' ) THEN 1
ELSE 0
END
ELSE
CASE
WHEN cfe_edi.etat <> '' THEN 1
ELSE 0
END
END = 1
AND cfe_edi.code_insee IS NOT NULL
AND cfe_edi.code_insee != ''
AND ( CASE
--WHEN CFE_EDI.CODE_INSEE IS NOT NULL AND CFE_EDI.CODE_INSEE !=''
--THEN CASE
WHEN ( #Destinataire = ''
OR #Destinataire IS NULL )
AND cfe_edi.code_insee = partenaires.code_insee
AND cfe_edi.dathrmaj > #DateCmt
AND cfe_edi.dathrmaj < #DateFin
AND cfe_edi.gestdel = '1' THEN 1
ELSE 0
END = 1
OR cfe_edi.code_insee = #Destinataire )
Also consider this evaluation AND cfe_edi.code_insee = partenaires.code_insee, is it necessary even if your JOIN operator is forcing to meet the condition? INNER JOIN dbo.CFE_EDI ON PARTENAIRES.CODE_INSEE = CFE_EDI.CODE_INSEE
A third option could be use a hidden parameter to clean the null and '' option of the user to produce a parameter populated with all values. Try the options above before get involved with hidden/internal parameter approach.
Let me know if this helps.

select NULL and false but not true in sql

i an new in vb.ner sql and what i am asking may be silly question. I have a table in sql server 2005 and a column name activated. this column contain NULL, true or false.
I want to select only NULL or false values. How can i do this?
The selection should be done on the SQL Server's side. Your query should look like this:
SELECT *
FROM MyTable
WHERE activated = 0 OR activated is NULL
The above assumes that the column activated is of an integral or a BIT data type.
Note: it may be tempting to use a seemingly equivalent WHERE activated <> 1 condition. This would be incorrect, though, because comparisons of NULL values to anything result in a NULL, so the rows with activated = NULL would be excluded.
You should be able to do a coalesce on the field to get it to false if it is null. A coalesce statement checks to see if the first parameter is null, if it is it returns the value in the second parameter. There would be two solutions:
SELECT *
FROM MyTable
WHERE COALESCE(activated,'false') <> 'true'`
--OR--
SELECT *
FROM MyTable
WHERE activated = 'false' or activated is null
With SQL's 3-valued logic, comparisons for NULL need to be done using the IS NULL operator... the check for false can be done with =:
SELECT YourColumn
FROM YourTable
WHERE
YourColumn IS NULL
OR YourColumn = 0
SELECT * FROM MyTable WHERE isnull(activated, 0) = 0
For checking NULL you have to use the keyword "IS NULL" and for false =0 like below
SELECT * FROM MyTable WHERE activated = 0 OR activated is NULL
Sometimes you have to see it to believe...
PRINT '0 = 0' ; IF 0 = 0 PRINT 'true' ELSE PRINT 'false';PRINT '';
PRINT '0 = 1' ; IF 0 = 1 PRINT 'true' ELSE PRINT 'false';PRINT '';
PRINT '0 = NULL' ; IF 0 = NULL PRINT 'true' ELSE PRINT 'false';PRINT '';
PRINT '1 = NULL' ; IF 1 = NULL PRINT 'true' ELSE PRINT 'false';PRINT '';
PRINT 'NULL = NULL' ; IF NULL = NULL PRINT 'true' ELSE PRINT 'false';PRINT '';
PRINT 'NULL IS NULL'; IF NULL IS NULL PRINT 'true' ELSE PRINT 'false';PRINT '';
The SQL way is to use IS TRUE or similar:
SELECT * FROM MyTable WHERE activated = 0 IS NOT FALSE

Check if condition before when in case statement

Case stud.Status
when 'N'then 'NA'
end
How to add following condition before when statement above
IF #ID is not equal to 2. That is I want to assign 'NA' only when also the id <> 2 plus the above condition.
EDIT: Full Query
Case Stud.Status
when #ID = 2 AND Stud.Status = 'N' then 'To Be Submitted'
when 'N'then 'N/A'
else isnull(Stud.Status, '')
end
Like this:
CASE
WHEN #ID <> 2 AND stud.Status ='N' THEN 'NA'
END
This is the other form of the CASE expression.
Note that: The CASE expression has two forms:
The simple CASE expression compares an expression to a set of simple expressions to determine the result.
The searched CASE expression evaluates a set of Boolean expressions to determine the result.
Update: Try this instead:
'StudStatus' =
CASE
WHEN #ID = 5 AND Stud.Status = 'N' THEN 'To Be Submitted'
WHEN Stud.Status = 'N' THEN 'N/A'
ELSE ISNULL(Stud.Status, '')
END
try this
Case stud.Status
when 'N' and #id<>2 then 'NA'
end
if #ID <> 2
begin
Case stud.Status
when 'N'then 'NA'
end
end

use an if...else statement as a return value in sql

I'm trying to write his in sql:
SET `Field` = (
If `Field` is empty then "b",
if `Field` is not empty, concat(`Field`,"_b"))
Meaning, if Field had value a it would change to a_b, if it was empty, it would change to b
Is there an sql synthax that creates this if..else statement properly?
IF(Field = "" or Field IS NULL,'b',concat(Field,'_b'))
You can use a CASE statement.
Example:
SELECT
CASE
WHEN myField IS NULL THEN 'b'
WHEN myField = '' THEN 'b'
ELSE myField + '_b'
END
FROM myTable
You need to use the CASE keyword.
Something like
UPDATE tbl
SET field =
CASE
WHEN field = ''
THEN 'b'
ELSE field + '_b'
END
You can use Cases but you can shorten it like this:
set Field = isnull(field, '')
+ case when isnull(field, '') = '' then '' else '_' end
+ 'b'