简体   繁体   中英

Where to insert a CASE statement in SQL?

The issue here is that while this works in SSMS, it fails when I post it onto a website that uses an SQL processing tool. I have narrowed it down to the first bolded segment in the C3 section. Use the code before that and it gives an error (like it should). Add that line and the site crashes. I have used other queries as an experiment and no problem. While I can't guarantee that it will work, it is my guess that it does not like that my periodyear field is char(4) and it can't do the implicit conversion from char to int and then back to char. So my question is where would I put the second bolded line in the C3 section (or before)?

WITH c1 AS
(SELECT e.stfips, e.areatype, e.area, e. periodyear, e.period, e.seriescode, e.empces
FROM ces as e
WHERE e.periodtype='03'
And e.supprecord='0'
and e.periodyear=
(Select Max(periodyear)
From ces)
and e.period=
(Select Top(1)period
From ces
Order by periodyear desc, period desc)
and e.stfips='32'
and e.adjusted='1'
and e.areatype='01'
),
C2 AS
(Select Distinct c1.periodyear, c1.period
From c1
),
C3 As
(Select
**(Case When c2.period='01' Then (c2.period + 11) Else (c2.period-1) END) As 'month',**
(Case When c2.period='01' Then (c2.periodyear -1) Else (c2.periodyear) END) As 'year'
From C2
),
C4 AS
(Select c.stfips, c.areatype, c.area, c.periodyear, c.period, c.seriescode, c.empces
From ces as c, c2
Where c.period = c2.period 
**And c.periodyear = ( cast ( cast(c2.periodyear as int) -1 ) as nvarchar(10) )**
And c.supprecord='0'
and c.stfips='32'
and c.adjusted='1'
and c.areatype='01'
),

You can use the year function rather than cast or implicit conversion

year(c.periodyear) = year(c2.periodyear)-1 

EDIT : (adding C3 section)

Select
    Case When c2.period='01' Then (c2.period + 11) Else (c2.period-1) END) As 'month',
    Case When c2.period='01' Then year(c2.periodyear) -1 Else year(c2.periodyear) END As 'year'
From C2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM