34,593
社区成员
发帖
与我相关
我的任务
分享
with cte as(select row_number() over(order by getdate()) as rowid,sname from 表)
update a set a.sname=case when a.rowid % 2=0 then (select left(sname,1) from cte where rowid=a.rowid-1)
else (select left(sname,1) from t where rowid=a.rowid+1) end+substring(a.sname,2,10)
from cte a
USE test
GO
-->生成表tb
if object_id('tb') is not null
drop table tb
Go
Create table tb([col1] nvarchar(3))
Insert into tb
Select N'李维一'
Union all Select N'张嘉凯'
Union all Select N'王小刚'
Union all Select N'采薇'
;WITH t AS (
SELECT *,ROW_NUMBER()OVER(ORDER BY GETDATE()) AS row FROM tb
)
SELECT
LEFT(ISNULL(b.col1,a.col1),1)+RIGHT(a.col1,LEN(a.col1)-1) AS col1
FROM t AS a
LEFT JOIN t AS b ON a.row=CASE WHEN a.row%2=1 THEN b.row-1 ELSE b.row+1 END
GO
/*
col1
----
张维一
李嘉凯
采小刚
王薇
*/
Create table #s (sname varchar(20))
insert into #s select '李维一'
union all select '张嘉凯'
union all select '王小刚'
union all select '采薇'
Create table #t (sname varchar(20))
insert into #t select '李维一'
union all select '张嘉凯'
union all select '王小刚'
union all select '采薇'
with t1 as (select sname,px=row_number()over(order by getdate()) from #s ),
t2 as (select sname,px=row_number()over(order by getdate()) from #t )
select * into #a from (
select name1,name2
from
(select sname as name1,px from t1 where px%2=1)a
join
(select sname as name2,px from t2 where px%2=0)b on a.px=b.px-1
union all
select name1,name2
from
(select sname as name1,px from t1 where px%2=0)a
join
(select sname as name2,px from t2 where px%2=1)b on a.px=b.px+1
)ab
--select * from #a
update #a set name1=left(ltrim(name1),1)+substring(ltrim(name2),2,len(ltrim(name2)))
select name1 from #a
避免逻辑复杂,我使用了临时表,把数据在临时表做好。再修改到实际表内
create table dbo.ded(sname varchar(20))
insert into dbo.ded(sname)
select '李维一' union all
select '张嘉凯' union all
select '王小刚' union all
select '采薇'
with t as
( select row_number() over(order by getdate()) 'rn',
sname
from dbo.ded
)
update a
set a.sname=case when a.rn%2=0 then (select left(sname,1) from t where rn=a.rn-1)
else (select left(sname,1) from t where rn=a.rn+1) end
+substring(a.sname,2,10)
from t a
select * from dbo.ded
/*
sname
--------------------
张维一
李嘉凯
采小刚
王薇
(4 row(s) affected)
*/