SQL Server, trying to get day of week via a deterministic UDF.
Im sure this must be possible, but cant figure it out.
UPDATE: SAMPLE CODE..
CREATE VIEW V_Stuff WITH SCHEMABINDING AS
SELECT
MD.ID,
MD.[DateTime]
...
dbo.FN_DayNumeric_DateTime(MD.DateTime) AS [Day],
dbo.FN_TimeNumeric_DateTime(MD.DateTime) AS [Time],
...
FROM {SOMEWHERE}
GO
CREATE UNIQUE CLUSTERED INDEX V_Stuff_Index ON V_Stuff (ID, [DateTime])
GO
Ok, i figured it..
Slightly similar approach to aforementioned solution, but just a one-liner that could be used inside a function or inline for computed column.
Assumptions:
If you'd rather it be different, change the date '18991231' to a date with the weekday that you'd like to equal 1. The convert() function is key to making the whole thing work - cast does NOT do the trick:
There is an already built-in function in sql to do it:
EDIT: If you really need deterministic UDF:
EDIT again: this is actually wrong, as
DATEPART(weekday)
is not deterministic.UPDATE:
DATEPART(weekday)
is non-deterministic because it relies onDATEFIRST
(source).You can change it with
SET DATEFIRST
but you can't call it inside a stored function.I think the next step is to make your own implementation, using your preferred DATEFIRST inside it (and not considering it at all, using for example Monday as first day).
Can't you just select it with something like:
The proposed solution has one problem - it returns 0 for Saturdays. Assuming that we're looking for something compatible with
DATEPART(WEEKDAY)
this is an issue.Nothing a simple
CASE
statement won't fix, though.The day of the week? Why don't you just use DATEPART?