Inline table-valued function without a parameter

前提是你 提交于 2020-01-06 12:37:51

问题


I am still pretty new to Azure platform, and learning SQL language. I have a question about creating a user-defined inline Table-valued function (without need a parameter) on Azure platform. Since accessing to Azure platform on my SQL Server Management Studio, whenever I create a log file by using the system built-in function GetDate(), it shows the date and time in UTC time zone, but I want my current time zone (Easter Time Zone) which is 4 hours behind of UTC. So, I am wondering if anyone can please guide me how I can create a inline-table-valued function that does not need any parameter, and able to use it as GetDate() function by simply running as below:

            SELECT GetDate() 

This is my attempt and I know this is not correct, but at least I tried.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[Azure_EST_GetDate()] (
)

RETURNS TABLE 
AS
RETURN 
(

    SELECT DATEADD(hh,-4,GETDATE()) AS 'handate'
)
GO

Thanks in advance,


回答1:


Consider using DATETIMEOFFSET and AT TIMEZONE instead of DATEADD. This will properly convert times across time zones and apply the appropriate time change rules. You can convert the DATETIMEOFFSET result to another type (datetime2 in this example) if needed.

I don't think your intent is to include the parenthesis in the function name so I removed it in this example.

CREATE FUNCTION [dbo].[Azure_EST_GetDate] (
)

RETURNS TABLE 
AS
RETURN 
(
    SELECT CAST(SYSDATETIMEOFFSET() AT TIME ZONE 'Eastern Standard Time' AS datetime2(3)) AS handate
);
GO

EDIT

A table-valued function can generally be used in queries wherever a table may be specified. For example:

SELECT handate FROM dbo.Azure_EST_GetDate();

Table-valued functions are appropriate when more than one column or row is returned. You could alternatively use a scalar function for your need since a scalar (single) value is returned. Below is the equivalent scalar function.

CREATE FUNCTION [dbo].[Azure_EST_GetDate_Scalar] ()
RETURNS datetime2(3)
AS
BEGIN
    RETURN CAST(SYSDATETIMEOFFSET() AT TIME ZONE 'Eastern Standard Time' AS datetime2(3));
END;
GO

This scalar function can be used instead of GETDATE() in Azure SQL Database to return a local time:

SELECT dbo.Azure_EST_GetDate_Scalar() AS handate;


来源:https://stackoverflow.com/questions/53027616/inline-table-valued-function-without-a-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!