--假设有一个表 归类项目表,有20个项目科目,
create table ITEMS
(id int not null ,
name char(20) not null
)
insert into ITEMS values (1,'项目1')
insert into ITEMS values (2,'项目2')
insert into ITEMS values (3,'项目3')
insert into ITEMS values (4,'项目4')
insert into ITEMS values (5,'项目5')
insert into ITEMS values (6,'项目6')
insert into ITEMS values (7,'项目7')
insert into ITEMS values (8,'项目8')
insert into ITEMS values (9,'项目9')
insert into ITEMS values (10,'项目10')
---还有一个表 明细项目
drop table ITEMDETAIL
create table ITEMDETAIL
( id int identity not null ,
name char(10) not null ,
price numeric(10,2) not null default 0 ,
item_id int not null
)
insert into ITEMDETAIL (name,price,item_id) values ('明细项目1',10,1)
insert into ITEMDETAIL (name,price,item_id) values ('明细项目2',10,2)
insert into ITEMDETAIL (name,price,item_id) values ('明细项目3',10,3)
--insert into ITEMDETAIL (name,price,item_id) values ('明细项目4',10,4)
insert into ITEMDETAIL (name,price,item_id) values ('明细项目5',10,5)
insert into ITEMDETAIL (name,price,item_id) values ('明细项目6',10,6)
insert into ITEMDETAIL (name,price,item_id) values ('明细项目7',10,7)
insert into ITEMDETAIL (name,price,item_id) values ('明细项目8',10,
insert into ITEMDETAIL (name,price,item_id) values ('明细项目9',10,9)
insert into ITEMDETAIL (name,price,item_id) values ('明细项目10',10,10)
--第三个表:销售项目明细表
drop table SALEDETAIL
create table SALEDETAIL
(orderno int identity not null ,--订单号
orderdate char( not null,--日期
invoiceno char(20) null,--发票号码
itemdetail_id int not null, --明细项目编码
item_id int not null, --归类大项目编码
price numeric(10,2) not null , --价格
num int not null, --数量
dept_no char(6) not null, --部门
amount numeric(10,2) not null
)
--其他字段就不说了
drop procedure usp_rpt_sale1
go
create procedure usp_rpt_sale1
@date_b char(, --开始日期
@date_e char( --截止日期
as
begin
declare @sqlstr1 varchar(8000), @sqlstr2 varchar(8000)
declare @id int , @name char(20)
select @sqlstr1 = 'select dept_no, '
--声明一个游标,以该游标控制动态语句的生成
declare cursor1 cursor for
select id ,name from ITEMS for read only
open cursor1
fetch cursor1 into @id, @name
select @sqlstr1 = @sqlstr1 + 'sum(case when itemdetail_id = ' + convert(varchar,@id)+ ' then amount else 0  as '+ @name + char(13)
fetch cursor1 into @id, @name
while @@fetch_status = 0
begin
select @sqlstr1 = @sqlstr1 + ' , sum(case when itemdetail_id =' + convert(varchar,@id)+ ' then amount else 0  as '+ @name + char(13)
fetch cursor1 into @id, @name
end
close cursor1
deallocate cursor1
--print @sqlstr1
select @sqlstr1 = @sqlstr1+ ', sum(amount) as "小计" ' + ' from SALEDETAIL where orderdate between "'+ @date_b + '" and "'+ @date_e + '" group by dept_no '
print @sqlstr1
--exec (@sqlstr1)
end