I have a table which nonsensically has DateTime values stored in Year (INT
), Month (INT
), Day (INT
) and Time (FLOAT
) columns; unfortunately I'm not allowed to change this but have a requirement to partition the table by Year and Month. Therefore, I am trying to create a persisted computed-column to hold the DateTime in a DATETIME2
format. However, my CreateDateTime
scalar function is being deemed as "non-deterministic" when I try to add a computed-column based upon it.
This is my CreateDateTime
function.
CREATE FUNCTION dbo.CreateDateTime
(
@year SMALLINT,
@month TINYINT,
@day TINYINT,
@time FLOAT
)
RETURNS DATETIME2
WITH SCHEMABINDING
AS
BEGIN
DECLARE @paddedYear VARCHAR(4) = FORMAT(@year, '0000')
DECLARE @paddedMonth VARCHAR(2) = FORMAT(@month, '00')
DECLARE @paddedDay VARCHAR(2) = FORMAT(@day, '00')
DECLARE @formattedTime VARCHAR(8) = FORMAT(@time, '00:00:00')
RETURN IIF
(
@year IS NULL
OR @month IS NULL
OR @day IS NULL,
NULL,
CAST
(
IIF
(
@time IS NULL OR TRY_CONVERT(TIME, @formattedTime) IS NULL,
@paddedYear
+ @paddedMonth
+ @paddedDay,
@paddedYear
+ @paddedMonth
+ @paddedDay
+ ' '
+ @formattedTime
)
AS DATETIME2
)
)
END
But when used in order to attempt to add the computed-column for DateTime (with the following script), it results in the following error message.
ALTER TABLE dbo.Logs
ADD [DateTime] AS (dbo.CreateDateTime(RY, RM, RD, RT)) PERSISTED
Computed column 'DateTime' in table 'Logs' cannot be persisted because the column is non-deterministic.
I've tried altering CreateDateTime
down to a very basic function which returns a fixed DateTime using the following: CAST('20000101' AS DATETIME2)
, CONVERT(DATETIME2, '20000101')
and '20000101'
but all produce the same error as above. I managed to get the column added though if I made the CreateDateTime
function return a VARCHAR(8)
instead so it looks like a problem with DATETIME2
.
How can I create this CreateDateTime
function so it is deemed as deterministic and still returns a DATETIME2
?