CREATE FUNCTION dbo.FN_GET_YEAR(@ID int) RETURNS int WITH SCHEMABINDING AS
BEGIN
RETURN (SELECT YEAR(begin_date) FROM dbo.tableName WHERE id = @ID);
END
GO
CREATE TABLE test_table (
id int,
fk_id int,
test AS dbo.FN_GET_YEAR(id)
);
SELECT COLUMNPROPERTY(OBJECT_ID('test_table'), 'test', 'IsIndexable') AS IsIndexableColumn;
The above is a very simplified extract of my actual problem. I have a function that returns the year of a given date and then that function is used as a computed column. I want the computed column to be indexable.
However, despite trying all the suggestions online, I am not sure what I am missing. I used the 'WITH SCHEMABINDING' key word and also tried with and without CONVERT/CAST. The problem is that the column is not deterministic, but documentation also says that YEAR() is deterministic.
If I simply return a static declared value in the function, then the column becomes indexable. YEAR() seems to break it.
EDIT:
I didn't want to post my original queries to keep things simple, but perhaps I made it too simple. I updated the function query closer to actual.