SQL Server - finding date difference in sql server using dynamic date value

Asked By raj on 14-Apr-14 05:46 AM


Hi,

I have some problem in finding date difference by retrieving the date value from the table with the help of dynamic date varible. but i am not able to finish it because of conversion error.

can any one help on this.

here i paste my code for your reference.

thanks in advance.

Declare
@instart int

declare @dt1 datetime,@fmm varchar(4),@too varchar(4)

declare @first datetime,@second datetime

declare @inout varchar(5)

declare @b VARCHAR(20)

 

declare @gg varchar(max)

 

declare @hours as int

declare @minutes as int

declare @seconds as int

declare @time_interval as nvarchar(10)

 

set @instart = 1

while @instart <= @inner

begin

 

set @fmm = 'dt'+cast(@instart-1 as varchar) –dynamically assign the table variable with @fmm ie., dt1 in table

set @too = 'dt'+cast(@instart as varchar) –dynamically assign the table variable with @too ie., dt2 in table

 

select @first = convert(datetime,@fmm) from table1 where empcode = 1 and (CONVERT(varchar, attndate, 101) = CONVERT(varchar, getdate()-1, 101))

 

select @second = convert(datetime,@@too) from table1 where empcode = 1 and (CONVERT(varchar, attndate, 101) = CONVERT(varchar, getdate()-1, 101))

 

set @hours = DATEDIFF(ss,@ first, @ second)/3600

 

set @instart = @instart + 1

 

Note: I am getting dynamically date value from the table based on the employeecode

I wanted to find the differece between two datetime ie., in the format HH:MM:SS hours,minutes and seconds.

 

When execute it, no error shows.

Command(s) completed successfully.

 

But when I run, it shows the error:

conversion failed when converting datetime from character string

Robbe Morris replied to raj on 14-Apr-14 07:39 AM
Why are you selecting a variable from a table?

select @first = convert(datetime,@fmm) from table1 where empcode = 1 and (CONVERT(varchar, attndate, 101) = CONVERT(varchar, getdate()-1, 101))

If you wanted to set @first equal to something you'd do this:

set @first = blah, blah, blah

As for @fmm, in this state of your code, that value would start with 'dt'.  That's not a valid datetime value.