SQL:与Function/Procedure合并计算?
SQL: Consolidate Calculation with Function/Procedure?
我有一段代码可以调整我的表格的日期。
dateadd(hh,
case
when
month(planned_start)=1 or
month(planned_start)=2 or
month(planned_start)=11 or
month(planned_start)=12 then -5
when
month(planned_start)=3 then
case
when datepart(hh,planned_start)<6 then -5
else -4
end
else -4
end
,planned_start)
基本上,我必须根据时差调整我的日期,但我需要调整 SQL 中多个位置的日期。现在,我只是将这段代码重复了大约 8 次。
有没有办法把它变成一个函数或过程,这样我就可以将 'planned_start' 发送到函数,运行 计算,然后 return '-4 或-5' 需要调整日期?
注意:我不相信我可以只使用变量,因为 'planned_start' 并且每行数据的小时偏移量可能不同。
谢谢。
这是您的查询的简化版本
SELECT Dateadd(hh, CASE
WHEN Month(planned_start) IN ( 1, 2, 11, 12 )
OR ( Datepart(hh, planned_start) < 6
AND Month(planned_start) = 3 ) THEN -5
WHEN Month(planned_start) = 3
AND Datepart(hh, planned_start) >= 6 THEN -4
ELSE -4
END, planned_start)
是的,您可以创建一个 function
并将其用于您的查询,而不是重复大量代码
CREATE FUNCTION dbo.Dateadjust (@DATE DATETIME)
RETURNS DATETIME
AS
BEGIN
DECLARE @result DATETIME; -- previously it was int
SELECT @result = Dateadd(hh, CASE
WHEN Month(@DATE) IN ( 1, 2, 11, 12 )
OR ( Datepart(hh, @DATE) < 6
AND Month(@DATE) = 3 ) THEN -5
WHEN Month(@DATE) = 3
AND Datepart(hh, @DATE) >= 6 THEN -4
ELSE -4
END, @DATE)
RETURN( @result );
END;
GO
在SELECT
语句中使用它
select planned_start,dbo.Dateadjust(planned_start)
From yourtable
我有一段代码可以调整我的表格的日期。
dateadd(hh,
case
when
month(planned_start)=1 or
month(planned_start)=2 or
month(planned_start)=11 or
month(planned_start)=12 then -5
when
month(planned_start)=3 then
case
when datepart(hh,planned_start)<6 then -5
else -4
end
else -4
end
,planned_start)
基本上,我必须根据时差调整我的日期,但我需要调整 SQL 中多个位置的日期。现在,我只是将这段代码重复了大约 8 次。
有没有办法把它变成一个函数或过程,这样我就可以将 'planned_start' 发送到函数,运行 计算,然后 return '-4 或-5' 需要调整日期?
注意:我不相信我可以只使用变量,因为 'planned_start' 并且每行数据的小时偏移量可能不同。
谢谢。
这是您的查询的简化版本
SELECT Dateadd(hh, CASE
WHEN Month(planned_start) IN ( 1, 2, 11, 12 )
OR ( Datepart(hh, planned_start) < 6
AND Month(planned_start) = 3 ) THEN -5
WHEN Month(planned_start) = 3
AND Datepart(hh, planned_start) >= 6 THEN -4
ELSE -4
END, planned_start)
是的,您可以创建一个 function
并将其用于您的查询,而不是重复大量代码
CREATE FUNCTION dbo.Dateadjust (@DATE DATETIME)
RETURNS DATETIME
AS
BEGIN
DECLARE @result DATETIME; -- previously it was int
SELECT @result = Dateadd(hh, CASE
WHEN Month(@DATE) IN ( 1, 2, 11, 12 )
OR ( Datepart(hh, @DATE) < 6
AND Month(@DATE) = 3 ) THEN -5
WHEN Month(@DATE) = 3
AND Datepart(hh, @DATE) >= 6 THEN -4
ELSE -4
END, @DATE)
RETURN( @result );
END;
GO
在SELECT
语句中使用它
select planned_start,dbo.Dateadjust(planned_start)
From yourtable