直接上代碼吧,根據不一樣的條件拼寫sql後並執行sql
ALTER PROCEDURE [dbo].[usp_Statistic_WJB_DZSK_ZT] ( @year int, @half int,--0表示整年,1表示上半年,2下半年 @isAll int --0表示只統計黨政幹部人員,1表示統計所有 ) as declare @sql nvarchar(4000) set @sql=N'select id from chgrwpj where id in(select distinct parentid from chgrymd' if(@isAll=0) set @sql=@sql + N' where ((unitcode between ''A0000'' and ''A0025'') or (unitcode between ''B0041'' and ''B0044'') or unitcode=''A1206'' or unitcode=''B0003'' or unitcode=''B0017'' or unitcode=''B0034'' or (unitcode=''B0045'' and positionLevel<=6 and positionLevel>0 and positionname<>''驗船師''))' set @sql=@sql + N') and innerAmount<chgrsh and year(enddate)=@year' if(@half=1) set @sql=@sql + N' and month(enddate) between 1 and 6 ' else if(@half=2) set @sql=@sql + N' and month(enddate) between 7 and 12' set @sql=@sql + N' order by senddate asc' exec sp_executesql @sql, N'@year int,@half int',@year,@half RETURN