获取错误从字符串转换日期和/或时间时转换失败

时间:2017-12-22 15:56:27

标签: sql-server sql-server-2008-r2

下面显示的查询导致错误

  

从字符串

转换日期和/或时间时转换失败

请帮帮我

SELECT 
    a.[Prod_id], a.[ctry_id], a.[ctry_cd],
    left(a.[re_ver],8) + ' (Per ' + a.[re_ver] + ')' as [re_ver],
    'YTD' as [per_type],
    sum(b.[unt_cas_cy_bp]) [unt_cas_cy_bp],
    sum(b.[unt_cas_cy_re]) [unt_cas_cy_re],
    sum(b.[unt_cas_py_act]) [unt_cas_py_act],
    sum(b.[unt_cas_2py_act]) [unt_cas_2py_act]
FROM  
    a
INNER JOIN
    b ON a.Prod_id = b.Prod_id 
      AND a.ctry_id = b.ctry_id 
      AND a.ctry_cd = b.ctry_cd
      AND b.per_type = 'Monthly'
      AND YEAR(LEFT(b.re_ver, 8)) * 100 + MONTH(LEFT(b.re_ver, 8)) 
              BETWEEN YEAR(LEFT(a.re_ver, 8)) * 100 + 1 
                  AND YEAR(LEFT(a.re_ver, 8)) * 100 + MONTH(LEFT(a.re_ver, 8)) 
WHERE
    a.per_type = 'Yearly'
GROUP BY
    a.[Prod_id], a.[ctry_id], a.[ctry_cd],
    a.[re_ver], a.[per_type]

1 个答案:

答案 0 :(得分:0)

问题是你的缩写可以是3或4个字符长。即九月缩写 Sept 。您正试图以奇怪的方式从此date字段创建varchar列,并且它不是可搜索的。相反,我会在CTE中进行转换,然后在where子句中使用它。

declare @badData table (re_ver varchar(64))
insert into @badData
values
('Feb 2017,Q4 2017'),
('Sept 2017,Q3 2016')

;with cte as(
select
    re_ver
    ,re_ver_date =  cast(
                        cast(case 
                            when left(re_ver,4) = 'Jan' then 1
                            when left(re_ver,4) = 'Feb' then 2
                            when left(re_ver,4) = 'Mar' then 3
                            when left(re_ver,4) = 'Apr' then 4
                            when left(re_ver,4) = 'May' then 5
                            when left(re_ver,4) = 'Jun' then 6
                            when left(re_ver,4) = 'Jul' then 7
                            when left(re_ver,4) = 'Aug' then 8
                            when left(re_ver,4) = 'Sept' then 9
                            when left(re_ver,4) = 'Oct' then 10
                            when left(re_ver,4) = 'Nov' then 11
                            when left(re_ver,4) = 'Dec' then 12
                        end as varchar(2))
                        + '/' 
                        + '01' 
                        + '/'
                        + cast(right(substring(re_ver,1,charindex(',',re_ver) - 1),4) as char(4))
                    as date)
from
    @badData)

select * 
from cte
--where <your condition>

我从'Mon YYYY'部分获得了一年,而不是查询中的Q# YYYY部分。但是,如果您想要季度部分中的年份,只需将最后一行更改为:

cast(right(re_ver,4) as char(4))