Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
kurtgr
Starting Member
25 Posts |
Posted - 2009-09-30 : 12:44:43
|
| I am getting this error when i use the DATEADD functionMsg 242, Level 16, State 3, Line 1The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.Below is the code i am usingDeclare @DatePart varchar(5), @UnitsToAdd int,@EffectiveDate SMALLDATETIMEset @DatePart = 'month'set @UnitsToAdd = 3set @EffectiveDate = getDate() declare @cmd nvarchar(255), @Parms nvarchar(255), @dt datetimeset @Parms = '@Units int,@Eff SmallDatetime, @dtOutput datetime OUTPUT'set @cmd = 'set @dtOutput = Dateadd(' + @DatePart + ',@Units,'+''''+Convert(Char(10),@EffectiveDate)+''''+')'exec sp_ExecuteSQL @cmd, @parms,@Units = @UnitsToAdd,@Eff = @EffectiveDate, @dtOutput = @dt OUTPUTselect @dtCan someone please assist me in saying what am i do wrongThanks in advance |
|
|
tkizer
Almighty SQL Goddess
38200 Posts |
|
|
kurtgr
Starting Member
25 Posts |
Posted - 2009-09-30 : 13:30:50
|
| Cause when passing the variables to the function I get errors especially with the first parameter |
 |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2009-09-30 : 13:35:22
|
| Convert(Char(10),@EffectiveDate) isn't a dateconvert(varchar(10),getdate(),112)JimEveryday I learn something that somebody else already knew |
 |
|
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2009-09-30 : 13:47:31
|
As you found out you can't use an parameter (or expression) as the datepart element of DATEADD. But rather than use dynamic sql, one possibility is to use a CASE to get the new date.select @dt = case @datepart when 'month' then dateadd(month, @unitsToAdd, @effectiveDate) when 'day' then dateadd(day, @unitsToAdd, @effectiveDate) --etc... end But besides Jim's observation you also would need to convert @units to varchar to concatenate the value into the @cmd string.Be One with the OptimizerTG |
 |
|
|
|
|
|
|
|