首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

简单的存储过程(求和,带四个输入参数)

2012-01-30 
求一个简单的存储过程(求和,带四个输入参数)表结构如下:表名:Reservoirs编号省份市县值idEnshengEnDiquEnX

求一个简单的存储过程(求和,带四个输入参数)
表结构如下:
表名:Reservoirs
编号         省份             市               县           值
id             Ensheng     EnDiqu       EnXian   Value

我现在想写个存储过程,两个参数   1:   Type(类别,1-省份,2-市,3-县)  
                                                              2:   Sheng(参数,省份名)
                                                              3:   Diqu   (参数,市名)
                                                              4:   Xian   (参数,县名)

输出结果为输入的省份或市、或县的记录总数

即内容为:区域名称(省份、市或县)+满足条件的记录数

条件当Type=1   条件为where   enshen=Sheng  
        当Type=2   条件为where   enshen=Sheng   and   endiqu=Diqu
        当Type=3   条件为where   enshen=Sheng   and   endiqu=Diqu   and   enxian=Xian  


[解决办法]
declare @tempsql varchar(2000)
declare @tempsql1 varchar(2000)
declare @tempsql2 varchar(2000)

if @Type=1
begin
@tempsql1= ' where enshen=Sheng '
@tempsql2= ' group by enSheng '
end
else
begin
if @type=2
begin
@tempsql1= ' where enshen=Sheng and endiqu=Diqu '
@tempsql2= ' group by enSheng,endiqu '
end
else
begin
if @type=3
begin
@tempsql1= ' where enshen=Sheng and endiqu=Diqu and enxian=Xian '
@tempsql2= ' group by enSheng,endiqum,xian '
end
end
end


set @tempsql= 'select sum(value) from Reservoirs '+@tempsql1+@tempsql2

exec(@tempsql)
[解决办法]
declare @tempsql varchar(2000)
declare @tempsql1 varchar(2000)
declare @tempsql2 varchar(2000)

if @Type=1
begin
@tempsql1= ' where enshen=Sheng '
@tempsql2= ' group by enSheng '
end
else
begin
if @type=2
begin
@tempsql1= ' where enshen=Sheng and endiqu=Diqu '
@tempsql2= ' group by enSheng,endiqu '
end
else
begin
if @type=3
begin
@tempsql1= ' where enshen=Sheng and endiqu=Diqu and enxian=Xian '
@tempsql2= ' group by enSheng,endiqum,enxian '
end
end
end


set @tempsql= 'select sum(value) from Reservoirs '+@tempsql1+@tempsql2

exec(@tempsql)

------解决方案--------------------


create procedure pro_demo @type varchar(50),@Sheng varchar(50),@Diqu varchar(50),@xian varchar(50)
AS
if ( @type = '1 ' )
begin
select count(*) from Reservoirs where enshen=@Sheng
end
else if (@type = '2 ')
begin
select count(*) from Reservoirs where enshen=@Sheng and endiqu=@Diqu
end
else
begin
select count(*) from Reservoirs where enshen=@Sheng and endiqu=@Diqu and enxian=@xian
end

GO
[解决办法]
declare @Type int
declare @tempsql varchar(2000)
declare @tempsql1 varchar(2000)
declare @tempsql2 varchar(2000)

if @Type=1
begin
set @tempsql1= ' where enshen=Sheng '
set @tempsql2= ' group by enSheng '
end
else
begin
if @type=2
begin
set @tempsql1= ' where enshen=Sheng and endiqu=Diqu '
set @tempsql2= ' group by enSheng,endiqu '
end
else
begin
if @type=3
begin
set @tempsql1= ' where enshen=Sheng and endiqu=Diqu and enxian=Xian '
set @tempsql2= ' group by enSheng,endiqum,enxian '
end
end
end


set @tempsql= 'select sum(value) from Reservoirs '+@tempsql1+@tempsql2

exec(@tempsql)

热点排行