--用存储过程--示例--示例数据
create table 销售表(销售日期 datetime,柜台号 varchar(10),金额 int)
insert 销售表 select '2004-10-10','aaa',20000
union all select '2004-10-10','bbb',35000
union all select '2004-10-10','ccc',40000
union all select '2004-10-11','aaa',38000
union all select '2004-10-11','bbb',46000
union all select '2004-10-11','ccc',50000create table 柜台表(编号 varchar(10),名称 varchar(10))
insert 柜台表 select 'aaa','食品柜'
union all select 'bbb','服装柜'
union all select 'ccc','家电柜'
union all select 'ddd','文化柜'
go--查询的存储过程
create proc p_qry
@编号 varchar(8000),
@开始日期 datetime,
@结束日期 datetime
as
declare @s varchar(8000),@tj varchar(100)
select @s=''
,@tj=' where 销售日期 between '''
+convert(char(10),@开始日期,120)
+''' and '''
+convert(char(10),@结束日期,120)
+''''
select @s=@s+',['+名称+']=sum(case 柜台号 when '''+编号+''' then 金额 else 0 end)'
from 柜台表 where charindex(','+编号+',',','+@编号+',')>0
exec('
select 销售日期=convert(char(10),销售日期,120)'+@s+'
from 销售表 '+@tj+'
group by convert(char(10),销售日期,120)')
go--调用
exec p_qry 'aaa,bbb,ccc','2004-10-10','2004-10-11'
go--删除测试
drop table 销售表,柜台表
drop proc p_qry/*--测试结果销售日期 食品柜 服装柜 家电柜
---------- ----------- ----------- -----------
2004-10-10 20000 35000 40000
2004-10-11 38000 46000 50000(所影响的行数为 2 行)
--*/
create table 销售表(销售日期 datetime,柜台号 varchar(10),金额 int)
insert 销售表 select '2004-10-10','aaa',20000
union all select '2004-10-10','bbb',35000
union all select '2004-10-10','ccc',40000
union all select '2004-10-11','aaa',38000
union all select '2004-10-11','bbb',46000
union all select '2004-10-11','ccc',50000create table 柜台表(编号 varchar(10),名称 varchar(10))
insert 柜台表 select 'aaa','食品柜'
union all select 'bbb','服装柜'
union all select 'ccc','家电柜'
union all select 'ddd','文化柜'
go--查询的存储过程
create proc p_qry
@编号 varchar(8000),
@开始日期 datetime,
@结束日期 datetime
as
declare @s varchar(8000),@tj varchar(100)
select @s=''
,@tj=' where 销售日期 between '''
+convert(char(10),@开始日期,120)
+''' and '''
+convert(char(10),@结束日期,120)
+''''
select @s=@s+',['+名称+']=sum(case 柜台号 when '''+编号+''' then 金额 else 0 end)'
from 柜台表 where charindex(','+编号+',',','+@编号+',')>0
exec('
select 销售日期=convert(char(10),销售日期,120)'+@s+'
from 销售表 '+@tj+'
group by convert(char(10),销售日期,120)')
go--调用
exec p_qry 'aaa,bbb,ccc','2004-10-10','2004-10-11'
go--删除测试
drop table 销售表,柜台表
drop proc p_qry/*--测试结果销售日期 食品柜 服装柜 家电柜
---------- ----------- ----------- -----------
2004-10-10 20000 35000 40000
2004-10-11 38000 46000 50000(所影响的行数为 2 行)
--*/
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货