MSSQL 存储过程中,如何解决需要拼接查询条件的问题

问题:

1、SQL语句太长,超过4000或8000个字符,用nvarchar(max),也有字符限制。

2、根据传入的参数不同,查询条件也不一样。

方法:

1、先将不需要拼接查询条件的查询结果存入临时表。

2、再根据传入参数,拼接查询条件,从临时表查询数据。

上代码:

 

declare @sSql nvarchar(max)

select @sSql = ' select * from #tmptable where 1=1 '

if @CRM_CustType != '' and @CRM_CustType != '0'
begin
select @sSql = @sSql + ' and crm_custid in (select crm_custid from crm_cust where CRM_CustType = '''+@CRM_CustType+''') '
end

if @CRM_CountyID != '' 

begin
select @sSql = @sSql + ' and crm_custid in (select crm_custid from crm_cust where (CRM_CountyID = '''+@CRM_CountyID+''' or CRM_CityID = '''+@CRM_CountyID+''' )) '
end

exec sp_executesql @sSql

posted @ 2020-07-10 17:29  建兵  阅读(316)  评论(0)    收藏  举报