这是可行的,但 UDF 必须是模式绑定。
有一个例子:
CREATE FUNCTION [dbo].[VitalyUTCtoDate] (@UTCDate DATETIME2)
RETURNS DATETIME2 WITH SCHEMABINDING AS
BEGIN
RETURN CASE WHEN @UTCDate < '9999-01-01' THEN DATEADD(HOUR, DATEDIFF(HOUR, GETUTCDATE(), GETDATE()), @UTCDate) ELSE NULL END;
END
GO
CREATE TABLE [dbo].[VitalyTest](
[ID] [bigint] IDENTITY(1,1) NOT NULL
,[Name] NVARCHAR(255) NOT NULL
,[Value] INT NULL
,[ValidFrom] DATETIME2 (2) GENERATED ALWAYS AS ROW START HIDDEN
,[ValidTo] DATETIME2 (2) GENERATED ALWAYS AS ROW END HIDDEN
,[WhenCreated] AS dbo.VitalyUTCtoDate(ValidFrom)
,CONSTRAINT [PK_VitalyTest] PRIMARY KEY CLUSTERED ([ID] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
,PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = [dbo].[VitalyTestHistory]))
GO