Avatar of emi_sastra
emi_sastra
 asked on

DateDiff dynamic sql command

Hi All,

I have below function.


 
ALTER Function dbo.DynamicDateDiff
  (@Interval VarChar(2),
   @Date1 DateTime,
   @Date2 DateTime)
Returns Int
As
Begin
  Return (Select Case @Interval
                   When 'w' Then DateDiff(WEEK, @Date1, @Date2)
                   When 'y' Then DateDiff(YEAR, @Date1, @Date2)
                           When 'd' Then DateDiff(DAY, @Date1, @Date2)
                            When 'm' Then DateDiff(MONTH , @Date1, @Date2)
                   End
         )
End


Is it correct ?

And I want to call it from sub query.

declare @ToDate Date = '20200101'



select a.Item
 , (SELECT DBO.DynamicDateDiff(''d'', A.TglJatuhTempo, ''' + @ToDate + ''')) AS HariJatuhTempo
from ItemMaster a


Is the sub query correct ?

Thank you.
Microsoft SQL Server

Avatar of undefined
Last Comment
emi_sastra

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
OMC2000

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
emi_sastra

ASKER
Hi Omc2000,

I try below code.


DECLARE @TODATE CHAR(8) = '20190221'

DECLARE @sql VARCHAR(MAX) = 'select TOP 1 NomorFkt, tglfkt
 , (SELECT DBO.DynamicDateDiff(''d'', A.TglJatuhTempo, ''' + @ToDate + ''')) AS HariJatuhTempo
from THINVSELL a'

print @sql
execute (@sql)

select TOP 1 NomorFkt, tglfkt
 , (SELECT DBO.DynamicDateDiff('d', A.TglJatuhTempo, '20190221')) AS HariJatuhTempo
from THINVSELL a
NomorFkt                       tglfkt                  HariJatuhTempo
------------------------------ ----------------------- --------------
NRJ-AU-2019-02-0024            2019-02-21 00:00:00.000 -90

(1 row(s) affected)

Why the result is  minus 90 ?

Thank you.
OMC2000

It must be due to the difference between selected  value of A.TglJatuhTempo and  '2019-02-21' equal to 90 days
emi_sastra

ASKER
My mistake.

Wrong column.

Thank you.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
emi_sastra

ASKER
Thank you very much.