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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 variable used in datediff

Author  Topic 

chih
Posting Yak Master

154 Posts

Posted - 2008-08-04 : 03:11:17
Hi everyone,

how can I correct this syntax
declare @d varchar(2)
set @d='d'
select datediff(@d,'2008-08-04 ','2008-08-06')

Thanks in advance.

dexter.knudson
Constraint Violating Yak Guru

260 Posts

Posted - 2008-08-04 : 03:44:00
Try this:
declare @d varchar(3), @sql nvarchar(4000)
set @d='day'
select @sql = ' select datediff(' + @d + ',''2008-08-04 '',''2008-08-06'')'
execute (@sql)
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2008-08-04 : 05:57:50
better use IF . . or CASE WHEN statement

IF @d = 'd' select datediff(day, . . .)
if @d = 'w' select datediff(week, . . .)

or
select case @d
when 'd' then datediff(day, . . )
when 'w' then datediff(day, . . )
end



KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

harlingtonthewizard
Constraint Violating Yak Guru

352 Posts

Posted - 2008-08-04 : 08:33:32
This maybe useful?
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=107666
Go to Top of Page
   

- Advertisement -