22,206
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([name] varchar(1),[id] int)
insert [tb]
select 'a',2 union all
select 'b',1 union all
select 'c',3
--------------------------------查询开始------------------------------
select b.* from [tb] b , master..spt_values s
where s.number between 1 and b.[id] and type='p'
/*
name id
---- -----------
a 2
a 2
b 1
c 3
c 3
c 3
(6 行受影响)
*/
if not object_id('tb') is null
drop table tb
Go
Create table tb([列1] nvarchar(1),[列2] int)
Insert tb
select N'a',2 union all
select N'b',1 union all
select N'c',3
Go
Select a.*
from tb a ,master..spt_values b
where b.number between 1 and [列2] and type='P'
/*
列1 列2
---- -----------
a 2
a 2
b 1
c 3
c 3
c 3
(6 個資料列受到影響)
*/
select k.*
from kof k join master..spt_values s
on k.col2>=s.number
where s.type='p' and s.number>0
order by col1
/*
col1 col2
---------- -----------
a 2
a 2
b 1
c 3
c 3
c 3
*/
select k.*
from kof k join master..spt_values s
on k.col2>=s.number
where s.type='p' and s.number between 1 and (select MAX(col2) from kof)
order by col1
/*
col1 col2
---------- -----------
a 2
a 2
b 1
c 3
c 3
c 3
*/