22,209
社区成员
发帖
与我相关
我的任务
分享
use Tempdb
go
--> -->
if not object_id(N'Tempdb..#') is null
drop table #
Go
Create table #([id] int,[groupiD] nvarchar(5))
Insert #
select 1,N'1' union all
select 2,N'1.1' union all
select 3,N'1.2' union all
select 4,N'1.1.1' union all
select 5,N'2' union all
select 6,N'2.1' union all
select 7,N'2.1.1' union all
select 8,N'2.2'
Go
;WITH c
AS
(
Select
*,
level=LEN([groupiD])-LEN(REPLACE([groupiD],'.','') )+1
from #
)
SELECT COUNT(*) AS 記錄數
FROM c a
WHERE EXISTS(SELECT 1 FROM c WHERE [groupiD]='2.1' AND level=a.level)
declare @gid varchar(10)
set @gid='2.1'
select * from tb
where len(groupiD)-len(replace('.',groupiD,''))=len(@gid)-len(replace('.',@gid,''))
/**
id groupiD
----------- -------
2 1.1
3 1.2
6 2.1
8 2.2
(4 行受影响)
**/
--> 测试数据:[A1]
if object_id('[A1]') is not null drop table [A1]
create table [A1]([card] int,[company_id] varchar(5))
insert [A1]
select 123456,'2.1' union all
select 234567,'2.2' union all
select 456567,'2.1.1'
select * from [A1]
SELECT * FROM A1 WHERE company_id LIKE '2.[0-9]'
/*
card company_id
----------- ----------
123456 2.1
234567 2.2
(2 行受影响)*/
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[groupiD] varchar(5))
insert [tb]
select 1,'1' union all
select 2,'1.1' union all
select 3,'1.2' union all
select 4,'1.1.1' union all
select 5,'2' union all
select 6,'2.1' union all
select 7,'2.1.1' union all
select 8,'2.2'
go
select *,len(groupiD)-len(replace('.',groupiD,'')) from tb
where len(groupiD)-len(replace('.',groupiD,''))=len('2.1')-len(replace('.','2.1',''))
/**
id groupiD
----------- ------- -----------
2 1.1 2
3 1.2 2
6 2.1 2
8 2.2 2
(4 行受影响)
**/
--> 测试数据:[TB]
if object_id('[TB]') is not null drop table [TB]
create table [TB]([id] int,[groupiD] varchar(5))
insert [TB]
select 1,'1' union all
select 2,'1.1' union all
select 3,'1.2' union all
select 4,'1.1.1' union all
select 5,'2' union all
select 6,'2.1' union all
select 7,'2.1.1' union all
select 8,'2.2'
select * from tb where groupid like '2.%' and len([groupiD])-len(replace([groupiD],'.',''))=1
/*
id groupiD
----------- -------
6 2.1
8 2.2
(2 行受影响)
*/
drop table [TB]
select * from tb where groupid like '2.[0-9]'