SQL SERVER 2008 根据参数的不同,执行不同的代码
1、
if 参数 = 值1 begin 执行代码1 end else if 参数 = 值1 begin 执行代码2 end else begin 执行代码3 end
2、goto 标签
3、
declare @busno varchar(10) = '0001' -- = 'ALL' -- = '' -- = null if ISNULL(@busno,'') in('ALL','') set @busno = '' select * from c_org_busi where busno like '%' + @busno + '%'
4、动态SQL(拼接)
SET QUOTED_IDENTIFIER OFF GO declare @busno_1 varchar(10)='0042',@year char(4) = '2022',@month varchar(2) = '8'; if OBJECT_ID('tempdb..#p') is not null drop table #p; select distinct m.saleno into #p from u_sale_m m(nolock) join u_sale_pay p(nolock) on m.saleno = p.saleno where m.accdate>=dateadd(month,-11,@year+RIGHT('0'+@month,2)+'01') and accdate < dateadd(month,1,@year+RIGHT('0'+@month,2)+'01') and p.paytype in('45','809080') create index i_#p on #p(saleno) if OBJECT_ID('tempdb..#d_category_move') is not null drop table #d_category_move; create table #d_category_move(period char(6),classname varchar(30),实收金额 numeric(18,4),毛利额 numeric(18,4),销售次数 int,毛利率 numeric(18,4)) declare @sql varchar(8000); set @sql = " select CONVERT(char(6),m.accdate,112) as period, c2.classname as classname, SUM((wareqty+minqty)*times*netprice) as 实收金额, SUM((wareqty+minqty)*times*netprice- (wareqty+minqty/stdtomin)*times*purprice) as 毛利额, COUNT(distinct c.saleno) as 销售次数, case when SUM((wareqty+minqty)*times*netprice) <> 0 then SUM((wareqty+minqty)*times*netprice- (wareqty+minqty/stdtomin)*times*purprice)/SUM((wareqty+minqty)*times*netprice) else 0 end as 毛利率 from u_sale_c c join v_busi_class v on c.busno = v.busno and v.groupid = '02' join u_ware_class wc(nolock) on c.wareid = wc.wareid and wc.parentcode = '01' join c_class c2(nolock) on wc.parentcode = c2.parentcode and left(wc.classcode ,4) = c2.classcode and c2.levels = 2 left join #p p on c.saleno = p.saleno join u_sale_m m on m.saleno = c.saleno where v.classcode = '01' " if @busno_1 <> 'all' and ISNULL(@busno_1,'') <> '' set @sql += " and m.busno = '" + @busno_1+"'"; set @sql += " and m.accdate >= dateadd(month,-11,'" + @year + "'+RIGHT('0'+'"+@month+"',2)+'01') and m.accdate < dateadd(month,1,'"+@year+"'+RIGHT('0'+'"+@month+"',2)+'01') and p.saleno is null group by CONVERT(char(6),m.accdate,112),c2.classname " insert into #d_category_move(period,classname,实收金额,毛利额,销售次数,毛利率) exec(@sql) select * from #d_category_move