create table Products
(物品名称 varchar(10),数量 int,单位 varchar(5),部门 varchar(10))insert into Products
select '振动砂',1,'台','木盒厂' union all
select '刨花机',2,'台','木盒厂' union all
select '万能锯',1,'台','木盒厂'
select a.物品名称,1 '数量',a.单位,a.部门
from Products a
cross apply
(select number from master.dbo.spt_values
where type='P' and number between 1 and a.数量) b/*
物品名称 数量 单位 部门
---------- ----------- ----- ----------
振动砂 1 台 木盒厂
刨花机 1 台 木盒厂
刨花机 1 台 木盒厂
万能锯 1 台 木盒厂(4 row(s) affected)
*/
select 物品名称,1 '数量',单位,部门 from Products a , master..spt_values b where
b.type='p' and b.number<a.数量 and a.数量>1
union all select 物品名称,1 '数量',单位,部门 from Products where 数量=1
版主的写法果然厉害
(物品名称 varchar(10),数量 int,单位 varchar(5),部门 varchar(10))insert into Products
select '振动砂',1,'台','木盒厂' union all
select '刨花机',2,'台','木盒厂' union all
select '万能锯',1,'台','木盒厂'select * into other_products
from Products
where 1<> 1
insert into other_products
select a.物品名称,1 '数量',a.单位,a.部门
from Products a
inner join master..spt_values t
on t.type='P' and t.number >0 and t.number<= 2 --2台
where a.物品名称 = '刨花机'
select * from other_products
/*
物品名称 数量 单位 部门
刨花机 1 台 木盒厂
刨花机 1 台 木盒厂
*/
go
create table #Products
(物品名称 varchar(10),数量 int,单位 varchar(5),部门 varchar(10))
insert into #Products
select '振动砂',1,'台','木盒厂' union all
select '刨花机',2,'台','木盒厂' union all
select '万能锯',1,'台','木盒厂'
---开始查询
select 物品名称,1 '数量',单位,部门 from #Products a , master..spt_values b where
b.type='p' and b.number<a.数量 and a.数量>1
union all select 物品名称,1 '数量',单位,部门 from #Products where 数量=1/*
物品名称 数量 单位 部门
---------------------
刨花机 1 台 木盒厂
刨花机 1 台 木盒厂
振动砂 1 台 木盒厂
万能锯 1 台 木盒厂
*/
select 物品名称,1 '数量',单位,部门 from Products a inner join master..spt_values b
on b.type='p' and b.number<a.数量
修改一下, 这样就可以啦
刨花机 有 2 台 所以,多增加一条记录到这个表里,成了2条:
刨花机 1 台 木盒厂
刨花机 1 台 木盒厂如果是只查询这两条记录,那就这样
select 物品名称,1 '数量',单位,部门 from Products a cross apply master..spt_values b where
b.type='p' and b.number<a.数量 and a.数量>1
select '刨花机',2,'台',N'木盒厂'
union all
select '万能锯',1,'台',N'木盒厂'
declare @wpmc nvarchar(60),@qty intdeclare @t table (wpmc nvarchar(30),qty int,dw nvarchar(1),bm nvarchar(200))
declare cur_hh cursor for select wpmc,qty from products
open cur_hh
fetch next from cur_hh into @wpmc,@qty
while @@fetch_status=0
begin
declare @i int
set @i=1
while(@i<=@qty)
begininsert into @t select wpmc,1,dw,bm from products where wpmc=@wpmc and qty=@qty
set @i=@i+1
set
end
fetch next from cur_hh into @wpmc,@qty
endselect * from @t
close cur_hh
deallocate cur_hh