如何为 DateDiff 动态传入 date_or_time_part?

How to dynamically pass in a date_or_time_part for DateDiff?

我有一列包含 "month""year" 等字符串,但是当我将其传递到 datediff 的第一个参数时,它没有说:

['COLUMN_NAME'] is not a valid date/time component for function DATEDIFF.

如何将 column_name 作为第一个参数作为 date_or_time_part 传递给 datediff,以便它可以动态设置时间单位?

date_or_time_part must be one of the values listed in Supported Date and Time Parts (e.g. month). The value can be a string literal or can be unquoted (e.g. 'month' or month).

您可以使用 CASE 表达式

case when mycolumn = 'month' then DATEDIFF(month,...)
    when mycolumn = 'year' then DATEDIFF(year,...)
end diff

试试这个..

Create table tblDateDifference(diffby  nvarchar(50),startdate  Date ,endDate  Date )

Insert into tblDateDifference(diffby,startdate,endDate) values('month','2022-01-29','2023-05-29')
Insert into tblDateDifference(diffby,startdate,endDate) values('year','2022-06-29','2023-01-29');
Insert into tblDateDifference(diffby,startdate,endDate) values('month','2020-01-19','2023-01-29');
Insert into tblDateDifference(diffby,startdate,endDate) values('year','2022-11-29','2023-01-29');
Insert into tblDateDifference(diffby,startdate,endDate) values('Days','2022-01-29','2023-01-29');

Select diffby,case when diffby='month' then dateDiff(month,startDate,endDate) 
when diffby='year' then  dateDiff(year,startDate,endDate) 
else  dateDiff(day,startDate,endDate) end Datedifference,startdate,enddate
 from tblDateDifference

你可以使用CASE的SWITCH语句形式,这样你只需要分支你想要的选项,匹配的就会被使用。

SELECT 
    date_from
    ,date_to
    ,part
    ,case part
       when 'month' then datediff('month', date_from, date_to) 
       when 'day' then datediff('day', date_from, date_to) 
       when 'hour' then datediff('hour', date_from, date_to) 
   end AS part_value
FROM VALUES 
('2021-12-21 12:30:00', '2022-01-30 12:30:00', 'month'),
('2022-01-21 12:30:00', '2022-01-30 12:30:00', 'day'),
('2022-01-30 10:30:00', '2022-01-30 12:30:00', 'hour')
v(date_from, date_to, part);
DATE_FROM DATE_TO PART PART_VALUE
2021-12-21 12:30:00 2022-01-30 12:30:00 month 1
2022-01-21 12:30:00 2022-01-30 12:30:00 day 9
2022-01-30 10:30:00 2022-01-30 12:30:00 hour 2