当前位置: 代码迷 >> Sql Server >> 更新求解,该如何处理
  详细解决方案

更新求解,该如何处理

热度:95   发布时间:2016-04-24 10:39:01.0
更新求解
现有一个表TableA ,字段 ID(key), Station(nvarchar),endTime(dateime), rdLong(int), RdDate(nvarchar)等
表中数据值:
1 3#筒仓 2014-01-01 05:45:52.530     9.00 NULL
2 3#筒仓 2014-01-02 07:36:15.937    9.00 NULL
3 1#筒仓 2014-01-03 15:08:18.780   42.00 NULL
4 1#筒仓 2014-01-04 18:08:08.970   42.00 NULL
5 1#筒仓 2014-01-05 21:08:04.767   43.00 NULL

现根据时间,如果时间大于07:30 小于17:30 则生成为 " 2014-01-02  日班" 放到对应的rddate字段中,
如果时间小于07:30 大于17:30 则生成为 " 2014-01-04  夜班" 放到对应的rddate字段中
最终生成格式
1 3#筒仓 2014-01-01 05:45:52.530     9.00 2014-01-01 夜班
2 3#筒仓 2014-01-02 07:36:15.937    9.00 2014-01-02  日班
3 1#筒仓 2014-01-03 15:08:18.780   42.00 2014-01-03  日班
4 1#筒仓 2014-01-04 18:08:08.970   42.00 2014-01-04 夜班
5 1#筒仓 2014-01-05 21:08:04.767   43.00 2014-01-05  夜班

请赐教
------解决方案--------------------
你的第一个记录错了,它应该是12-31 的夜班.
create table TableA(ID int, Station nvarchar(10),endTime datetime,rdLong int , RdDate nvarchar(20))
go
insert into tablea select 1,'3#筒仓','2014-01-01 05:45:52.530',9.00,null
insert into tablea select 2,'3#筒仓','2014-01-02 07:36:15.937',9.00,null
insert into tablea select 3,'1#筒仓','2014-01-03 15:08:18.780',42.00,null
insert into tablea select 4,'1#筒仓','2014-01-04 18:08:08.970',42.00,null
insert into tablea select 5,'1#筒仓','2014-01-05 21:08:04.767',43.00,null
go
update TableA set RdDate=
(case when convert(varchar(5),endTime,114)>'17:30' then convert(varchar(10),endTime,120)+' 夜班' 
when convert(varchar(5),endTime,114)<'07:30' then convert(varchar(10),dateadd(d,-1,endTime),120)+' 夜班'
else convert(varchar(10),endTime,120)+' 日班'
end)
select * from tablea
/*
ID          Station    endTime                 rdLong      RdDate
----------- ---------- ----------------------- ----------- --------------------
1           3#筒仓       2014-01-01 05:45:52.530 9           2013-12-31 夜班
2           3#筒仓       2014-01-02 07:36:15.937 9           2014-01-02 日班
3           1#筒仓       2014-01-03 15:08:18.780 42          2014-01-03 日班
4           1#筒仓       2014-01-04 18:08:08.970 42          2014-01-04 夜班
5           1#筒仓       2014-01-05 21:08:04.767 43          2014-01-05 夜班

(5 行受影响)

*/
go
drop table tablea

------解决方案--------------------
update dbo.Table1 set RdDate=
case when convert(varchar(5),endTime,114)>'07:30' and  convert(varchar(5),endTime,114)<'17:30' 
then convert(varchar(10),endTime,120)+'日班' 
else convert(varchar(10),endTime,120)+'夜班' end 
  相关解决方案