
我有如上图一数据表。
如何通过SQL截取出A04内容,(表内A04值现为空,需我填写)
------解决方案--------------------
create table #t(A01 varchar(50), A02 int, A03 int);
insert into #t
select '10112004410', 1, 1 union all
select '10112004410', 2, 2 union all
select '10112004410', 3, 1 union all
select '10112004410', 4, 2 union all
select '10112004410', 5, 1 union all
select '10112004410', 6, 2 union all
select '10112004410', 7, 2 union all
select '101120048', 1, 1 union all
select '101120048', 2, 2 union all
select '101120048', 3, 1 union all
select '101120048', 4, 2 union all
select '101120048', 5, 1 union all
select '101120048', 6, 2;
with t as
(
select A01, A02, A03, LEFT(A01, A03) AS A04,
RIGHT(A01, LEN(A01)-A03) t
from #t
where A02=1
union all
select #t.A01, #t.A02, #t.A03, LEFT(t.t, #t.A03),
RIGHT(t.t, LEN(t.t)-#t.A03) t
from #t join t on #t.A01=t.A01 and #t.A02=t.A02+1
)
select A01, A02, A03, A04
from t
order by A01, A02
drop table #t
/*-------结果-------------
A01 A02 A03 A04
--------------------------
10112004410 1 1 1
10112004410 2 2 01
10112004410 3 1 1
10112004410 4 2 20
10112004410 5 1 0
10112004410 6 2 44
10112004410 7 2 10
101120048 1 1 1
101120048 2 2 01
101120048 3 1 1
101120048 4 2 20
101120048 5 1 0
101120048 6 2 48
------------------------*/
------解决方案--------------------
create table #t(A01 varchar(50), A02 int,
A03 int, A04 varchar(10)
);
insert into #t(A01, A02, A03)
select '10112004410', 1, 1 union all
select '10112004410', 2, 2 union all
select '10112004410', 3, 1 union all
select '10112004410', 4, 2 union all
select '10112004410', 5, 1 union all
select '10112004410', 6, 2 union all
select '10112004410', 7, 2 union all
select '101120048', 1, 1 union all
select '101120048', 2, 2 union all
select '101120048', 3, 1 union all
select '101120048', 4, 2 union all
select '101120048', 5, 1 union all
select '101120048', 6, 2;
with t as
(
select A01, A02, A03, LEFT(A01, A03) AS A04,
RIGHT(A01, LEN(A01)-A03) t
from #t
where A02=1
union all
select #t.A01, #t.A02, #t.A03, LEFT(t.t, #t.A03),
RIGHT(t.t, LEN(t.t)-#t.A03)
from #t join t on #t.A01=t.A01 and #t.A02=t.A02+1
)
update #t set A04=t.A04
from #t join t ON t.A01=#t.A01 AND t.A02=#t.A02;
select * from #t
order by A01, A02
drop table #t
/*-------结果-------------
A01 A02 A03 A04
--------------------------
10112004410 1 1 1
10112004410 2 2 01
10112004410 3 1 1
10112004410 4 2 20
10112004410 5 1 0
10112004410 6 2 44
10112004410 7 2 10
101120048 1 1 1
101120048 2 2 01
101120048 3 1 1
101120048 4 2 20
101120048 5 1 0
101120048 6 2 48
------------------------*/
------解决方案--------------------
就像版主说的,你想要截取的字符串长度比字符串总长度还大的时候,出现这个错误。
改一个写法可以让程序运行,但是毕竟你的数据有问题呀。
我把倒数第二行A03改成了5,改了写法得到以下结果
create table #t(A01 varchar(50), A02 int,
A03 int, A04 varchar(10)
);
insert into #t(A01, A02, A03)
select '10112004410', 1, 1 union all