22,209
社区成员
发帖
与我相关
我的任务
分享
create table tb(kmdm varchar(10),kmmx int)
insert into tb values('101' ,null)
insert into tb values('102' ,null)
insert into tb values('10201' ,null)
insert into tb values('10202' ,null)
insert into tb values('10203' ,null)
insert into tb values('103' ,null)
go
update tb set kmmx = (case when exists (select 1 from tb where charindex(t.kmdm,kmdm) > 0 and t.kmdm <> kmdm) then 0 else 1 end) from tb t
select * from tb
drop table tb
/*
kmdm kmmx
---------- -----------
101 1
102 0
10201 1
10202 1
10203 1
103 1
(所影响的行数为 6 行)
*/
--> 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(kmdm int, kmmx int)
insert into #
select 101, 1 union all
select 102, 1 union all
select 10201, 1 union all
select 10202, 1 union all
select 10203, 1 union all
select 103, 1
-- 全变1了是吧?那把有下级明细的找出来,UPDATE为0
update # set kmmx = 0 from # t where exists (select 1 from # where kmdm<>t.kmdm and ltrim(kmdm) like ltrim(t.kmdm)+'%')
select * from #
/*
kmdm kmmx
----------- -----------
101 1
102 0
10201 1
10202 1
10203 1
103 1
*/