SQL case statement in a stored procedure - sql-server

I have a SQL Server stored proc that contains a CASE statement. However, I need to append the values if multiple conditions are true.
So if a particular record has an Invalid Date And Mileage exceeded, I would like both values to be displayed in the NotArchiveableReason column.
How would I accomplish that?
, CASE
WHEN DateOfLoss < PolicyStartDate THEN 'Invalid Date'
WHEN MilesDriven > TotalMilesAllowed THEN 'Mileage exceeded'
WHEN LossStatusCode != 'R' THEN 'Status code is Review'
Else 'Unknown issue'
END
As NotArchiveableReason

If you want to concatenate results like Invalid Date, Mileage Exceeded then you may be looking for something like this.
ISNULL(
NULLIF(
STUFF(
CASE WHEN DateOfLoss < PolicyStartDate THEN ', Invalid Date' ELSE '' END
+ CASE WHEN MilesDriven > TotalMilesAllowed THEN ', Mileage exceeded' ELSE '' END
+ CASE WHEN LossStatusCode != 'R' THEN ', Status code is Review' ELSE '' END
, 1, 2, '')
,'')
, 'Unknown issue')
As NotArchiveableReason
The STUFF() removes the leading comma. The NULLIF() converts the empty string to null. The ISNULL() will populate "Unknown Issue" when none of the CASE statement conditions are met.

, CASE WHEN DateOfLoss < PolicyStartDate THEN 'Invalid Date ' ELSE '' END
+ CASE WHEN MilesDriven > TotalMilesAllowed THEN 'Mileage exceeded ' ELSE '' END
+ CASE WHEN LossStatusCode != 'R' THEN 'Status code is Review ' ELSE '' END
+ CASE WHEN NOT
( DateOfLoss < PolicyStartDate
AND MilesDriven > TotalMilesAllowed
AND LossStatusCode != 'R') THEN 'Unknown issue ' ELSE '' END
As NotArchiveableReason

, CASE WHEN DateOfLoss < PolicyStartDate THEN 'Invalid Date ' ELSE '' END
+ CASE WHEN MilesDriven > TotalMilesAllowed THEN 'Mileage exceeded ' ELSE '' END
+ CASE WHEN LossStatusCode != 'R' THEN 'Status code is Review ' ELSE '' END
CASE WHEN DateOfLoss >= PolicyStartDate OR MilesDriven <= TotalMilesAllowed
OR LossStatusCode = 'R'
THEN 'Unknown issue' END As NotArchiveableReason

How about expand the result set and let the application handle it
, CASE WHEN DateOfLoss < PolicyStartDate THEN 1 ELSE 0 END as InvalidDate
, CASE WHEN MilesDriven > TotalMilesAllowed THEN 1 ELSE 0 END as MileageExceeded
, CASE WHEN LossStatusCode != 'R' THEN 1 ELSE 0 END as StatusCodeIsReview
Then if all is zero it is an unknown issue?
EDIT
You can try this then. This is using an inner select to first find the problems and then combine it afterwards. In this sollution you can add many different checks in the inner select, and then combine them as you like in the outer.
select case when tmp.InvalidDate is null and tmp.MileageExceeded is null and tmp.StatusCodeIsReview is null then 'Unknown issue' else
stuff
(
(
COALESCE(', ' + NULLIF(tmp.InvalidDate, ''), '') +
COALESCE(', ' + NULLIF(tmp.MileageExceeded, ''), '') +
COALESCE(', ' + NULLIF(tmp.StatusCodeIsReview, ''), '')), 1, 2, '')
end as NotArchiveableReason from
(
select *
, CASE WHEN DateOfLoss < PolicyStartDate THEN 'Invalid Date' ELSE NULL END as InvalidDate
, CASE WHEN MilesDriven > TotalMilesAllowed THEN 'Mileage Exceeded' ELSE NULL END as MileageExceeded
, CASE WHEN LossStatusCode != 'R' THEN 'Status Code Is Review' ELSE NULL END as StatusCodeIsReview
from MyTest
) as tmp

Why dont you go with 3 case statements and then in a new query CONCAT them?
, CASE
WHEN DateOfLoss < PolicyStartDate THEN 'Invalid Date'
END as 1
WHEN MilesDriven > TotalMilesAllowed THEN 'Mileage exceeded'
END as 2
WHEN LossStatusCode != 'R' THEN 'Status code is Review'
END as 3
select 1+2+3 As NotArchiveableReason

Related

Using CASE in #Parameters

How can I use case when .. then in #Parameters in MS Report Builder?
For example this code does not work correct, because Filter does not work
SELECT DISTINCT case
when [APPROVAL_STATUS] = 'approved' then '1'
when [APPROVAL_STATUS] = 'denied' then '2'
when [APPROVAL_STATUS] = 'pending' then '3'
when isnull([APPROVAL_STATUS], ' ') = '' then '4'
ELSE [APPROVAL_STATUS]
end as [APPROVAL_STATUS]
FROM [dbo].[SUMMARY]
Is it possible?

Using Pentaho Report Designer how to display data in a line

Using Pentaho Report Designer I want to take data from columns in a database and have this data displayed in a line.
See my example below. Is there a way I can accomplish this?
My database table looks like this:
GENUS SPECIFIC_EPITHET SPECIES_AUTHOR
Asplenium scolopendrium L.
Asplenium bradleyi D.C. Eaton
Asplenium platyneuron (L.) Britton, Sterns & Poggenb.
Asplenium viride Huds.
I would like the report to look like this:
Asplenium scolopendrium L., Asplenium bradleyi D.C. Eaton, Asplenium platyneuron (L.) Britton, Sterns & Poggenb., Asplenium viride Huds.
I am only able to get the report to show the data in a column like list as shown below.
Asplenium scolopendrium L.
Asplenium bradleyi D.C. Eaton
Asplenium platyneuron (L.) Britton, Sterns & Poggenb.
Asplenium viride Huds.
It would also be helpful if someone would tell me if this is not possible in PRD.
I figured this out thanks to being shown how by Deanicus on the Pentaho Reporting Forum (see here).
The main trick was to query my database before I got my data into the report via PRD. Since I am working with a POSTGRESQL database the code I used to query the database looked something like this.
SELECT
string_agg(CONCAT(CONCAT(CONCAT(
c."genus", ' '),
c."specific_epithet",' '),
c."species_author"),', ') as scinamewauthor
FROM
"public"."main_checklist" as c
My final query was actually a lot more complicated since I was adding all sorts of spaces and html formatting marks. The entire piece of code actually looks like this.
SELECT
string_agg (CONCAT(
(SELECT CASE WHEN s."genus_synonym" IS NULL THEN '' ELSE '<i>'||s."genus_synonym"||'</i>' END),
(SELECT CASE WHEN s."specific_epithet_synonym" IS NULL THEN '' ELSE ' <i>'||s."specific_epithet_synonym"||'</i>' END),
(SELECT CASE WHEN s."species_author_synonym" IS NULL THEN '' ELSE ' '||s."species_author_synonym" END),
(SELECT CASE WHEN s."subspecific_epithet_synonym" IS NULL THEN '' ELSE ' ssp. '||'<i>'||s."subspecific_epithet_synonym"||'</i>'END),
(SELECT CASE WHEN s."subspecies author_synonym" IS NULL THEN '' ELSE ' '|| s."subspecies author_synonym" END),
(SELECT CASE WHEN s."varietal_epithet_synonym" IS NULL THEN '' ELSE ' var. <i>'||s."varietal_epithet_synonym"||'</i>' END),
(SELECT CASE WHEN s."variety_author_synonym" IS NULL THEN '' ELSE ' '|| s."variety_author_synonym" END),
(SELECT CASE WHEN s."misapplied" = 'misapplied hybrid formula 1' THEN ' misapplied' ELSE '' END),
(SELECT CASE WHEN s."hybrid_formula_genus_synonym" is null THEN '' ELSE ' × <i>'||substring("hybrid_formula_genus_synonym" from 1 for 1)||'.</i>'END),
(SELECT CASE WHEN s."hybrid_formula_specific_epithet_synonym" is null THEN '' ELSE ' <i>'|| s."hybrid_formula_specific_epithet_synonym"||'</i>' END),
(SELECT CASE WHEN s."hybrid_formula_species_author_synonym" is null THEN '' ELSE ' '||s."hybrid_formula_species_author_synonym" END),
(SELECT CASE WHEN s."hybrid_formula_subspecific_epithet_synonym" IS NULL THEN '' ELSE ' ssp. <i>'||s."hybrid_formula_subspecific_epithet_synonym"||'</i>' END),
(SELECT CASE WHEN s."hybrid_formula_subspecies_author_synonym" IS NULL THEN '' ELSE ' '||s."hybrid_formula_subspecies_author_synonym" END),
(SELECT CASE WHEN s."hybrid_formula_varietal_epithet_synonym" IS NULL THEN '' ELSE ' var. <i>'||s."hybrid_formula_varietal_epithet_synonym"||'</i>'END),
(SELECT CASE WHEN s."hybrid_formula_variety_author_synonym" IS NULL THEN '' ELSE ' '||s."hybrid_formula_variety_author_synonym"END),
(SELECT CASE WHEN s."misapplied" = 'misapplied hybrid formula 2' THEN ' misapplied' ELSE '' END),
(SELECT CASE WHEN s."genus_hybrid_synonym" IS NULL THEN '' ELSE '×'End),
(SELECT CASE WHEN s."hybrid_name_genus_synonym" IS NULL THEN ''
WHEN s."genus_synonym" IS NULL THEN '<i>'||s."hybrid_name_genus_synonym"||'</i>'
Else ' = <i>'||"hybrid_name_genus_synonym" ||'</i>'END),
(SELECT CASE WHEN s."hybrid_name_specific_epithet_synonym" IS NULL THEN ''
when s."genus_hybrid_synonym" is null then ' ×<i>'||s."hybrid_name_specific_epithet_synonym"||'</i>'
ELSE ' <i>'||s."hybrid_name_specific_epithet_synonym"||'</i>' END),
(SELECT CASE WHEN s."hybrid_name_species_author_synonym" IS NULL THEN '' ELSE ' '||s."hybrid_name_species_author_synonym" END),
(SELECT CASE WHEN s."hybrid_name_subspecific_epithet_synonym" IS NULL THEN '' ELSE ' ssp. <i>'||s."hybrid_name_subspecific_epithet_synonym"||'</i>'END),
(SELECT CASE WHEN s."hybrid_name_subspecies_author_synonym" IS NULL THEN '' ELSE ' '||s."hybrid_name_subspecies_author_synonym"END),
(SELECT CASE WHEN s."hybrid_name_varietal_epithet_synonym" IS NULL THEN '' ELSE ' var. <i>'||s."hybrid_name_varietal_epithet_synonym"||'</i>'END),
(SELECT CASE WHEN s."hybrid_name_variety_author_synonym" IS NULL THEN '' ELSE ' 'END),
s."hybrid_name_variety_author_synonym",
(SELECT CASE WHEN (s."misapplied" IS NULL or s."misapplied" = 'misapplied hybrid formula 1' or s."misapplied" = 'misapplied hybrid formula 2') Then ''
WHEN s."misapplied" = 'misapplied hybrid name' Then ' misapplied'
Else ' '||"misapplied" END)),
', '
Order by s."genus_synonym" ASC,
s."specific_epithet_synonym" ASC,
s."varietal_epithet_synonym" ASC NULLS FIRST,
s."subspecific_epithet_synonym" ASC NULLS FIRST,
s."hybrid_formula_specific_epithet_synonym" ASC,
s."hybrid_formula_subspecific_epithet_synonym" ASC,
s."hybrid_formula_varietal_epithet_synonym" ASC,
s."hybrid_name_specific_epithet_synonym" ASC)as syno
FROM
"public"."synonyms" as s INNER JOIN "public"."main_checklist" ON s."record_id" = "public"."main_checklist"."record_id"
WHERE
s."record_id" = ${import_record_id}

Concat the table records based on the condtion

I am building a SSRS Report to show Student Class Information.
I have a table named class with information regarding classes students were attended.
My requirement is to show the days in which the classes occur. For eg: If Column Name Monday = 'Y' then I have to show the day as [Mon]. I have tried below code .
SELECT
case when Monday ='Y' then'[Mon]' else '' end +case when Monday ='Y' then ',' else '' end +
case when Tuesday ='Y' then'[Tue]' else '' end +case when Tuesday ='Y' then ','else '' end +
case when Wednesday='Y' then'[Wed]' else '' end +case when Wednesday ='Y' then ',' else '' end +
case when Thursday ='Y' then'[Thu]' else '' end +case when Thursday ='Y' then ',' else '' end +
case when Friday ='Y' then'[Fri]' else '' end +case when Friday ='Y' then ',' else '' end +
case when Saturday ='Y' then'[Sat]' else '' end +case when Saturday ='Y' then ',' else '' end +
case when Sunday ='Y' then'[Sun]' else '' end as classday
FROM vw_Class_Without_Instructor
I got the output as below.
In output there is an extra comma at the end of each line. Any way to exclude it in the select statement itself?. Is there any other way to get the output?. Use of case statements seems to be slow down the execution.
Please try this below query
SELECT
SUBSTRING(case when Monday ='Y' then',[Mon]' else '' end +
case when Tuesday ='Y' then',[Tue]' else '' end +
case when Wednesday='Y' then',[Wed]' else '' end +
case when Thursday ='Y' then',[Thu]' else '' end +
case when Friday ='Y' then',[Fri]' else '' end +
case when Saturday ='Y' then',[Sat]' else '' end +
case when Sunday ='Y' then',[Sun]' else '' end, 2,200) as classday
FROM vw_Class_Without_Instructor
trick: I've added commas with text so no half number of case evaluations. With ,[Mon] value I've ensured that there is always a comma in beginning which is removed using SUBSTRING.
be wise to choose a very high value in last part parameter of SUBSTRING so that it return everything starting from the charindex in second part.
See msdn reference: https://msdn.microsoft.com/en-us/library/ms187748.aspx
If the sum of start and length is greater than the number of
characters in expression, the whole value expression beginning at
start is returned.
You can try this;
select
CASE WHEN LEN(classday_with_comma) > 0 THEN LEFT(classday_with_comma,LEN(classday_with_comma) - 1) ELSE '' END as classday
From (
SELECT
case when Monday = 'Y' then '[Mon],' else '' end +
case when Tuesday = 'Y' then '[Tue],' else '' end +
case when Wednesday = 'Y' then '[Wed],' else '' end +
case when Thursday = 'Y' then '[Thu],' else '' end +
case when Friday = 'Y' then '[Fri],' else '' end +
case when Saturday = 'Y' then '[Sat],' else '' end +
case when Sunday = 'Y' then '[Sun],' else '' end as classday_with_comma
FROM vw_Class_Without_Instructor
) as x
Two case statement can be truncated to one from
case when Monday ='Y' then'[Mon]' else '' end +
case when Monday ='Y' then ',' else '' end +
To
case when Monday = 'Y' then '[Mon],' else '' end +
And
LEFT(classday_with_comma, LEN(classday_with_comma) - 1)
will remove the last ,

How to retrieve only those column from a table corresponding to which a particular value is present in other column in another table in sql query

I have two tables in a database ,namely main.vacuum_status and main_vacuum_analog. **
logtime is a common field
of both the tables.
In main.vacuum_status there are column namely and st1_vs1_bag1_onoff..in this way there are eight columns upto st1_vs1_bag8_onoff.Some of these columns have 0 or 1 as a value respectively.In another table there are columns st1_vs1_bag1_rb till st1_vs1_bag8_rb with some real type values.
Condition
Now I want a sql query which check whenever there is 1 in st1_vs1_bag1_onoff.. columns then the real type values of another table column st1_vs1_bag1_rb...should be dispalyed.i.e if st1_vs1_bag8_onoff is 0 then st1_vs1_bag8_rb should not be displayed and if st1_vs1_bag8_onoff is 1 then the value of st1_vs1_bag8_rb sholud be displayed.
Is there any such sql query??
EDIT 1
By looking at the answers ,I formed my sql query as
select
case when a.st1_vs1_bag1_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag1_rb ELSE 'Value when 0' END as st1_vs1_bag1_rb ,
CASE when a.st1_vs1_bag2_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag2_rb else '0' END as st1_vs1_bag1_rb ,
CASE when a.st1_vs1_bag3_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag3_rb else '0' END as st1_vs1_bag1_rb ,
CASE when a.st1_vs1_bag4_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag4_rb else '0' END as st1_vs1_bag1_rb ,
CASE when a.st1_vs1_bag5_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag5_rb else '0' END as st1_vs1_bag1_rb ,
CASE when a.st1_vs1_bag6_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag6_rb else '0' END as st1_vs1_bag1_rb ,
CASE when a.st1_vs1_bag7_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag7_rb else '0' END as st1_vs1_bag1_rb ,
CASE when a.st1_vs1_bag8_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag8_rb else '0' END as st1_vs1_bag1_rb ,
from main_vacuum_status a INNER JOIN main_vacuum_analog c ON a.LOGTIME = c.LOGTIME
But error is being shown Incorrect syntax near form
Based on the information you provided, you could do something like the following :
SELECT
CASE WHEN st1_vs1_bag1_onoff = 1 THEN st1_vs1_bag1_rb END AS st1_vs1_bag1_rb
CASE WHEN st1_vs1_bag2_onoff = 1 THEN st1_vs1_bag2_rb END AS st1_vs1_bag2_rb
CASE WHEN st1_vs1_bag3_onoff = 1 THEN st1_vs1_bag3_rb END AS st1_vs1_bag3_rb
CASE WHEN st1_vs1_bag4_onoff = 1 THEN st1_vs1_bag4_rb END AS st1_vs1_bag4_rb
CASE WHEN st1_vs1_bag5_onoff = 1 THEN st1_vs1_bag5_rb END AS st1_vs1_bag5_rb
CASE WHEN st1_vs1_bag6_onoff = 1 THEN st1_vs1_bag6_rb END AS st1_vs1_bag6_rb
CASE WHEN st1_vs1_bag7_onoff = 1 THEN st1_vs1_bag7_rb END AS st1_vs1_bag7_rb
CASE WHEN st1_vs1_bag8_onoff = 1 THEN st1_vs1_bag8_rb END AS st1_vs1_bag8_rb
FROM main_vacuum_status S
INNER JOIN main_vacuum_analog A
ON S.logtime = A.logtime
if st1_vs1_bag*_onoff is different than 1, st1_vs1_bag*_rb will be NULL.
If you want to display a default value instead, put it in the ELSE part, like this :
CASE WHEN st1_vs1_bag1_onoff = 1 THEN st1_vs1_bag1_rb ELSE 'Value when 0' END AS st1_vs1_bag1_rb
You can do the following :
SELECT LOGTIME
,
,CASE
WHEN st1_vs1_bag1_onoff = 1
THEN st1_vs1_bag1_rb
ELSE '<No Value>'
END AS st1_vs1_bag1_rb
,
.
.
.
.
.
.
,CASE
WHEN st1_vs1_bag8_onoff = 1
THEN st1_vs1_bag8_rb
ELSE '<No Value>'
END AS st1_vs1_bag8_rb
FROM main.vacuum_status AL1
INNER JOIN main_vacuum_analog AL2 ON AL1.LOGTIME = AL2.LOGTIME
Let me know if this is not what you are looking for.
I got what I wanted through this query,both the above answers were helpful:))
select c.LOGTIME,
case when a.st1_vs1_bag1_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag1_rb ELSE '0' END as st1_vs1_bag1_rb ,
CASE when a.st1_vs1_bag2_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag2_rb else '0' END as st1_vs1_bag2_rb ,
CASE when a.st1_vs1_bag3_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag3_rb else '0' END as st1_vs1_bag3_rb ,
CASE when a.st1_vs1_bag4_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag4_rb else '0' END as st1_vs1_bag4_rb ,
CASE when a.st1_vs1_bag5_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag5_rb else '0' END as st1_vs1_bag5_rb ,
CASE when a.st1_vs1_bag6_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag6_rb else '0' END as st1_vs1_bag6_rb ,
CASE when a.st1_vs1_bag7_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag7_rb else '0' END as st1_vs1_bag7_rb ,
CASE when a.st1_vs1_bag8_onoff='0' and a.logtime=c.logtime then c.st1_vs1_bag8_rb else '0' END as st1_vs1_bag8_rb
from main_vacuum_status a INNER JOIN main_vacuum_analog c ON a.LOGTIME = c.LOGTIME and
c.logtime between '2014-10-10 07:17:00' and '2014-10-10 08:46:00'

Retun x character AFTER a string SQL Server

I'm trying to return the following 4 characters after a string in a column 'E.Notes'
Example string 'Code: ABCD'
Target output 'ABCD'
I've tried to no avail ;-(
CASE WHEN CHARINDEX('<strong>Code:</strong> ', E.Notes) > 0 THEN
LEFT(E.Notes, CHARINDEX('<strong>Code:</strong> ', E.Notes) 4)
ELSE '' END
USE SUBSTRING() OR RIGHT() SHOULD BE OK.
CASE WHEN CHARINDEX('<strong>Code:</strong> ', E.Notes) > 0 THEN
SUBSTRING(E.Notes, CHARINDEX('<strong>Code:</strong> ', E.Notes) + LEN('<strong>Code:</strong> '), 255)
ELSE '' END
CASE WHEN CHARINDEX('<strong>Code:</strong> ', E.Notes) > 0 THEN
RIGHT(E.Notes,LEN( E.Notes) + 1 - LEN('<strong>Code:</strong>') - CHARINDEX('<strong>Code:</strong> ', E.Notes) )
ELSE '' END
AND YOU CAN USE RTRIM() OR LTRIM() TO GET RID OF SPACES.
Try this
DECLARE #Notes VARCHAR(200) = '<strong>Code:</strong> ABCDkkkk'
SELECT CASE
WHEN CHARINDEX('Code:', #Notes) > 0
THEN RIGHT(#Notes, LEN(#Notes) - CHARINDEX('Code:', #Notes) - 14)
ELSE ''
END
EDITED
By OP's demand to get only first 4 character from the string.
SELECT CASE
WHEN CHARINDEX('Code:', #Notes) > 0
THEN LEFT(RIGHT(#Notes, LEN(#Notes) - CHARINDEX('Code:', #Notes) - 14), 4)
ELSE ''
END

Resources