求助一个更新现有数据的SQL语句
我原来的数据表已经存在了很多业务数据,现在因为需要增加了一个流水号字段,这个流水号字段需要按照现有的表里的创建日期加"PO"前缀,再加一串数字自动生成。
比如:PO20130325001,PO20130325002。
我原来的表结构
Pid PName CreateTime
----- -------- ------------------------
1 采购单1 2013-03-25 15:22:00
2 采购单2 2013-03-25 17:13:15
3 文具 2013-03-26 10:10:01
4 圆珠笔 2013-03-26 11:07:24
我的新的表结构
Pid PNo PName CreateTime
----- ------------ -------- ------------------------
1 PO20130325001 采购单1 2013-03-25 15:22:00
2 PO20130325002 采购单2 2013-03-25 17:13:15
3 PO20130326001 文具 2013-03-26 10:10:01
4 PO20130326002 圆珠笔 2013-03-26 11:07:24
怎样通过SQL来给这个新加的字段更新值呢?
------解决方案--------------------select 'PO'+convert(varchar,createtime,23)+right('0000'+
convert(varchar,row_number() over(partition by convert(varchar,createtime,23) order by id)),4) from tb
------解决方案--------------------create table #a (id varchar(20),name varchar(10),date datetime)
insert into #a(name,date) values('a','2013-2-1')
insert into #a(name,date) values('b','2013-2-3')
insert into #a(name,date) values('c','2013-4-1')
insert into #a(name,date) values('d','2013-4-7')
UPDATE #a SET id=R1.ID FROM (
select 'PO'+CONVERT(VARCHAR(8),date,112)+'000'+CAST(ROW_NUMBER() OVER(PARTITION BY CONVERT(VARCHAR(6),date,112) order by name ) AS VARCHAR) AS ID,name,date
from #a
)R1
SELECT * FROM #a
drop table #a
id name date
PO201302010001 a 2013-02-01 00:00:00.000
PO201304070002 b 2013-02-03 00:00:00.000
PO201302010001 c 2013-04-01 00:00:00.000
PO201304070002 d 2013-04-07 00:00:00.000
------解决方案--------------------首先要保证PID为唯一值,要不然就加个自动增长的主键好了
如果PID未按是排序可将第三行PID换成createtime
update po_table set pno=xh.poid from
(
select 'PO'+convert(varchar(8),createtime,112)+
rgiht('000'+cast((row_number() over(order by convert(varchar(8),createtime,112),pid)-RANK()
over (order by convert(varchar(8),createtime,112)))+1 as varchar(3)),3) as poid ,pid from
po_table) xh where po_table.pid=xh.pid