procedure和Function中动态SQL

 经常需要在procedure和Function中把参数作为查询条件作为动态的SQL,但procedure和Function有一些不同。

procedure:

DECLARE @nsql NVARCHAR(500)
DECLARE @i INT
SET @nsql = 'SELECT 1 FROM Rep_Fact_AvgSingleSample_Temp WHERE gid_SystemFactory = @gid_SystemFactory ';
	if(@gid_waveInfo IS NOT NULL)
		SET @nsql = @nsql + ' AND gid_waveInfo = @gid_waveInfo';
	if(@WaveName IS NOT NULL)
		SET @nsql = @nsql + ' AND WaveName = @WaveName';
	if(@gid_Areainfo IS NOT NULL)
		SET @nsql = @nsql + ' AND gid_Areainfo = @gid_Areainfo';
	if(@ObjectName IS NOT NULL)
		SET @nsql = @nsql + ' AND ObjectName = @ObjectName';

	SET @nsql  = @nsql + ' AND YearName = @YearName AND QuarterInfo = @QuarterInfo AND gid_Factory_QuestionList = @gid_Factory_QuestionList AND CycleType = @CycleType AND ObjectType = @ObjectType AND SelfLayer = @SelfLayer';
	exec sp_executesql @nsql;
	select @i = @@rowcount

 

但是在function中不能使用exec sp_executesql,所以需要使用另外一种方法

--1,若是采用动态语句
declare @sql varchar(1000)
set @sql='select * from tb where 1=1 '
if @p1 is not null
  set @sql=@sql + ' and field1=' + @p1
if @p2 is not null
  set @sql=@sql + ' and field2=' + @p2

--2,若是采用的非动态语句
select * from tb 
  where field1=case when @p1 is null then field1 else @p1 end
       and field2=case when @p2 is null then field2 else @p2 end


这样我就能使用下面的语句:

	IF EXISTS ( SELECT 1 FROM Rep_Fact_AvgSingleSample_Temp WHERE gid_SystemFactory = @gid_SystemFactory AND 
				gid_waveInfo = case when @gid_waveInfo is null then gid_waveInfo else @gid_waveInfo end AND
				WaveName = case when @WaveName is null then WaveName else @WaveName end AND
				gid_Areainfo = case when @gid_Areainfo is null then gid_Areainfo else @gid_Areainfo end AND
				ObjectName = case when @ObjectName is null then ObjectName else @ObjectName end AND
				YearName = @YearName AND QuarterInfo = @QuarterInfo AND gid_Factory_QuestionList = @gid_Factory_QuestionList AND 
				CycleType = @CycleType AND ObjectType = @ObjectType AND SelfLayer = @SelfLayer)   
	BEGIN 
		SELECT @ReturnValue = '1';
	END	

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值