你可以将变量传递到 DATEDIFF 的区间吗

Can you pass a variable into the interval of DATEDIFF

我感觉我已经知道答案了,但是你可以做下面的事情吗(最基本的例子)

DECLARE @interval varchar(2) = 'yy'

SELECT DATEDIFF(@interval, myDate, GETDATE())

我将单位(yy、mm 或 dd)保存在一列中,并希望根据其他列之一动态地 运行 DATEDIFF,通过间隔。

你不能。您需要使用 case 表达式:

select (case @interval
            when 'year' then datediff(year, mydate, getdate())
            when 'month' then datediff(month, mydate, getdate())
            when 'day' then datediff(day, mydate, getdate())
        end)

我应该说。您可以使用动态SQL,但对于这种类型的计算来说,这通常不必要地复杂。

select case @interval
            when 'yy' then datediff(year, mydate, getdate()) end as 'YEAR'
 case @interval
            when 'mm' then datediff(month, mydate, getdate()) end as 'MONTH'
 case @interval
            when 'dy' then datediff(day, mydate, getdate())end as 'DAY'

确保 Day 没有像 'dd' 和 month 'mm' 一样的关键字 参考https://www.w3schools.com/sql/func_sqlserver_datediff.asp