sql server - Conditional CASE/IF in constructing T-SQL statement -
i have query in front-end code i'm trying convert stored procedure. front-end code has conditional logic in construct correct sql based on form values. did not write original sql have been tasked conversion.
the issue i'm facing don't have enough knowledge/experience go doing this. have consulted these links help, don't quite me there:
sql: conditional statement in group clause
sql case statement specifiying condition in clause?
pseudo-code:
where b.active=1 , year(metric_year) = @frmyear if @selorg not null , @selorg != 'all' if @selorg = 'org1' , org in('org1','org2','org3') , measure_id not in(0,1,2,3,4) else , org = @selorg else , measure_id not in(0,1,2,3,4)
trying simple results in "incorrect syntax near end" error.
where b.active=1 , year(metric_year) = @frmyear , case @selorg when 'org1' org in('org1','org2','org3') , measure_id not in(0,1,2,3,4) end
is want possible? if so, failing see?
you this:
where b.active=1 , year(metric_year) = @frmyear , ( (@selorg = 'org1' , org in('org1','org2','org3') , measure_id not in(0,1,2,3,4)) or (@selorg = 'all') )
depending on criteria going though may beneficial separate queries -
if @selorg = 'org1' begin select ... table b.active=1 , year(metric_year) = @frmyear , org in('org1','org2','org3') , measure_id not in(0,1,2,3,4); end else if @selorg = 'all' begin select ... table b.active=1 , year(metric_year) = @frmyear; end
this may seem work, may improved performance.
Comments
Post a Comment