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

浙公网安备 33010602011771号