sql server - Reading a string expression with parameters and executing the expression as date -


i trying create dynamic code date calculation in sql stored procedures having problems executing string expressions , parameters date expressions.

i want hold generic string expressions in table create dates according value of parameters.

for example generic expression :

dateadd(@timeresolution, -@iterationn, @currentcalc)  

as can see these generic expressions composed out of parameters to.

in stored procedures intend declare variables in expression , assign values them using select statement different table.

the problem after deriving these string values , writing expression not give me date want fails.

so example if write following code

declare @today date  declare @lastyear date set @today = getdate()  set @lastyear =  dateadd(year, -1, @today) select @lastyear 

it works fine , last year's date.

but when try :

declare @today date   declare @lastyear date  declare @timeresolution varchar(5)  select @timeresolution =  [timeresolution] dbo.mytable rule_id=1//timeresolution varchar column in table holding values 'year' or 'month'  declare iteration int  select @iteration  =  [iteration] dbo.mytable rule_id=1 //iteration int column in table holding values  1 or 2, or 3  set @today = getdate()  set @lastyear =  dateadd(timeresolution , -iteration , @today)   select @lastyear 

this gives me conversion error.

is there way create such dynamic date expressions?

it isn't possible use variable interval in dateadd, can this:

if @timeresolution = 'year' begin     set @lastyear =  dateadd(year, -@iteration , @today)  end  if @timeresolution = 'month' begin     set @lastyear =  dateadd(month, -@iteration , @today)  end 

Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -