我停留在转换varchar列计划,其中包含以下数据0,1,2,3,4,8,9,10,11,12,15,16,17,18 ,19到INT。我知道,请不要问为什么这个计划专栏最初没有创建为INT,长篇大论。
所以我尝试了这个,但它不起作用。并给我一个错误:
select CAST(schedule AS int) from shift_test:
查询应检查是否在使用下面的SQL代码提交的计划中找到代表天数的数字
select empid, case when ((DateDiff(hour,'01-01-2014 07:00' , '01-01-2014 00:00')/ 24 )% 15) in ( CAST(schedule AS int))
then 'A' else '*' end as shift_A from Shift_test
执行后我收到此错误。
将varchar值转换为int时转换失败。
任何帮助都会受到欢迎
答案 0 :(得分:0)
如果您使用的是版本2008或2008R2,请使用ISNUMERIC()
测试。在SQL SERVER 2012中,您可以使用TRY_CAST()
函数,该函数检查是否允许给定文字进行数据转换。
模拟SQL Server 2008 / R2的代码:
Select col1, col2,
case
when <condition> and isnumeric(col2) then cast(col2 as int)
else <do whatever...>
end
as converted_col2
from <yourtable>;
对于SQL Server 2012:
Select col1, col2,
case
when <condition> then try_cast(col2 as int)
else <do whatever...>
end
as converted_col2
from <yourtable>;
SQl Server 2008示例
declare @T table (empid int, schedule varchar(2)) ;
insert into @T(empid, schedule) values (1, '1');
insert into @T(empid, schedule) values (2, '2');
insert into @T(empid, schedule) values (3, '03');
insert into @T(empid, schedule) values (4, '4');
insert into @T(empid, schedule) values (5, '05');
insert into @T(empid, schedule) values (6, 'A');
select empid,
case
when ISNUMERIC(schedule) = 1
and ((DateDiff(hour,'01-01-2014 07:00' , '10-01-2014 00:00')/ 24 )% 15)
in ( CAST(schedule AS int)) then 'A'
else '*'
end
as shift_A
from @T;
答案 1 :(得分:0)
@Binaya我添加了我的代码以获得更多帮助。
计划列包含(0,1,2,3,4,8,9,10,11,12,15,16,17,18,19),它们是varchar。
我想输出 A ,如果在此计算后((DateDiff(hour,'01-01-2014 07:00',startdate)/ 24 )% 15)
,则在计划列中找到结果,如果在计算后找不到结果输出 * < / p>
;with Shift_runover (shift_code,schedule,endd,startdate)
-- Start at the beginning of shift.
as
(select shift_code,schedule,Cast(end_date as DateTime) as endd,Cast(start_date as DateTime)as startdate from dbo.Shift_test
union all
-- Add hours up to the desired end date.
select shift_code,schedule,endd,DateAdd(hour, 1,startdate)from Shift_runover where startdate<=endd),
Extendedsamples as
(
-- Calculate the number of days since the beginning of the first shift on 1/1/2014.
select shift_code,schedule,startdate,DateDiff(hour,'01-01-2014 07:00',startdate)/ 24 as Days from Shift_runover ),
Shifts as
(
-- the schedule column contain (0, 1, 2, 3,4,8,9,10,11,12,15,16,17,18,19) which is varchar.
-- i want to output A if ((DateDiff(hour,'01-01-2014 07:00',startdate)/ 24 )% 15) is found in the schedule colume
select *,
case when (DateDiff(hour,'01-01-2014 07:00',startdate)/ 24 )% 15 in(schedule)
then 'A' else '*' end as shift_A
from ExtendedSamples
)
select *
from Shifts
option ( maxrecursion 0 )