日期:2014-05-17 浏览次数:20913 次
/********************************************************************************
*主题: SQl 2008/2005 论坛问题解答
*说明:本文是个人学习的一些笔记和个人愚见
* 有很多地方你可能觉得有异议,欢迎一起讨论
*作者:Stephenzhou(阿蒙)
*日期: 2012.08.7
*Mail:szstephenzhou@163.com
*另外:转载请著名出处。
**********************************************************************************/
--字段A有空也有带数值的
--如何把空值的部分加上数值
--要求
--1、不能重复
--2、按2000000000001起增加,2000000000002,2000000000003....
--3、效率要高,因为字段A可能有十万行数据。
--4、执行语句遇到死机等特殊情况时,能否对数据库避免产生影响。
--SQL2005 谢谢!
--输入测试数据
use DBText
go
if OBJECT_ID('tb_test') is not null
drop table tb_test
go
create table tb_test(id int identity primary key,A varchar(50))
go
declare @i int;
set @i=0;
while @i<300
begin
if right (DATEPART(ms,GETDATE()),1)=0
insert into tb_test values('test'+cast(@i as varchar));
else
insert into tb_test values(null);
set @i=@i+1
end
go
--查看测试数据
select * from tb_test
/*
id A
----------- --------------------------------------------------
1 NULL
2 NULL
3 test2
4 test3
5 test4
6 test5
7 test6
8 test7
9 test8
10 test9
11 test10
12 test11
13 test12
14 test13
15 test14
16 test15
17 test16
18 test17
.
.
.
.
38 test37
39 NULL
40 NULL
41 NULL
42 NULL
43 NULL
44 NULL
45 NULL
46 NULL
47 NULL
48 NULL
49 NULL
...
...
..
297 NULL
298 NULL
299 NULL
300 NULL
*/
--按照LZ说的情况更新
declare @str varchar(50)
set @str='2000000000000'
update tb_test set A=m.Ae from
(
select t.id as id ,t.A as A ,f.id as fid ,f.A as fA ,f.Ae as Ae from tb_test t left join (
select * ,Ae=(left(@str,len(@str)-LEN(s.rn))+CAST(s.rn as varchar)) from
( select * ,ROW_NUMBER()over(partition by A order by id) as rn from tb_test where A is null )s )f on f.id=t.id)m
where tb_test.A is null and tb_test.id=m.id
---输出更新后的结果集合
select * from tb_test
/*
id A
----------- --------------------------------------------------
1 2000000000001
2 2000000000002
3 2000000000003
4 2000000000004
5 2000000000005
6 2000000000006
7 test6
8 test7
9 test8
10 test9
11 2000000000007
12 2000000000008
13 2000000000009
14 2000000000010
15 2000000000011
16 2000000000012
17 2000000000013
18 2000000000014
19 2000000000015
20 2000000000016
21 2000000000017
22 2000000000018
23 2000000000019
24 2000000000020
25 2000000000021
26 2000000000022
27 2000000000023
28 2000000000024
29 2000000000025
30 2000000000026
31 2000000000027
32 2000000000028
33 2000000000029
34 2000000000030
35 2000000000031
36 2000000000032
37 2000000000033
38 2000000000034
39 2000000000035
40 2000000000036
41 2000000000037
42 2000000000038
43 2000000000039
44 2000000000040
45 test44
46 test45
47 test46
48 test47
49 test48
50 test49
51 test50
52 test51
53 test52
54 test53
55 test54
56