动态执行脚本的存储过程

需要从一个价格库表中,根据条件查询出相应的价格信息。价格库表结构如下:

create table T_PriceLibrary
(
PLId int IDENTITY(1,1), --自价格库ID
MaterialId int, --已报价物料Id
SupplierId int, --已报价供应商Id
PriceType int, --价格类型
Price decimal(13, 6), --价格
QuoteYear int, --年份
QuoteMonth int, --月份
constraint PK_T_PriceLibrary primary key(PLId)
)
go


由于该表中可能会存在,同一年份,同一月份出现,同种价格类型出现多条记录,但是,在查询价格时,每个月份只需要查询最新的记录就可以,存储过程如下:

-----------------------------
--
描叙:根据条件查询价格库价格的信息
--
范小军
--
2012-03-07
--
---------------------------
if exists(select 1 from sysobjects where type='p' and name='P_T_PriceLibrary_Select')
drop proc P_T_PriceLibrary_Select
go

create proc P_T_PriceLibrary_Select
(
@materialid nvarchar(50),
@beginyear int,
@beginmonth int ,
@endyear int ,
@endmonth int ,
@datatype int ,
@sourcefiled nvarchar(50),
@filterfiled nvarchar(50),
@filtervalue nvarchar(50),
@msg nvarchar(50)='' output
)
as
declare @sql nvarchar(max),@listplid nvarchar(200),@tempbmonth int
begin
set @listplid='' --保存满足条件的主键的集合
set @tempbmonth=@beginmonth
while @tempbmonth<=@endmonth
begin
declare @tempstr nvarchar(20) ,@tempsql nvarchar(200),@COUNT nvarchar(20)
set @tempsql='select @COUNT =max(PLId)from T_PriceLibrary where QuoteMonth='+cast(@tempbmonth as nvarchar)+' and QuoteYear='+cast(@beginyear as nvarchar)+' and MaterialId='+char(39)+@materialid+char(39) +'and PriceType='+cast(@datatype as nvarchar)+' and '+ @filterfiled+' = '+char(39)+@filtervalue+char(39)
--根据条件查询满足条件的主键的最大值,如果同一月份,出现多条记录,取最新的记录,也就是PLId最大的值
execute sp_executesql 
@tempsql, 
N'@COUNT nvarchar(20) OUTPUT',
@COUNT=@tempstr OUTPUT --将动态执行脚本执行的结果赋值给定义的变量
if @tempstr is null begin --判断一个字符串是否为空
set @tempstr=0
end
select @tempstr=@tempstr+','
print cast(@tempstr as nvarchar)
select @listplid=cast(@listplid as nvarchar)+cast(@tempstr as nvarchar)--在进行变量相加时,该变量,必须先赋予初始值,不然为null,追加还是null
print @listplid
set @tempbmonth=@tempbmonth+1
end
set @listplid=Left(@listplid,Len(@listplid)-1) --去掉最后一个字符
select @sql= 'select '+@sourcefiled+' ,QuoteMonth from T_PriceLibrary where PLId in('+ @listplid+') and MaterialId='+char(39)+@materialid+char(39)+'and PriceType='+cast(@datatype as nvarchar)+' and QuoteYear='+cast(@beginyear as nvarchar)+' and QuoteMonth between '+cast(@beginmonth as nvarchar)+' and '+cast(@endmonth as nvarchar)+' and '+ @filterfiled+' = '+char(39)+@filtervalue+char(39)+''
--@listplid最为满足条件的主键集合条件
Exec sp_executesql @sql 
if @@ERROR<>0
begin
rollback tran a
set @msg=@msg+'数据读取失败!';
return 1
end
else
begin
set @msg=@msg+'数据读取成功!'
return 0
end
end
go
原文地址:https://www.cnblogs.com/fanxiaojun/p/2385672.html