Здравствуйте, barboss, Вы писали:
B>Как бы сделать такую скалярку детерминированной ?
Например так (ключевое — явно использовать CONVERT со стилем подходящим под детерминированность):
ALTER FUNCTION dbo.func()
RETURNS DATETIME
WITH SCHEMABINDING
AS
BEGIN
--RETURN ( '2024-01-22' )
RETURN CONVERT(DATETIME, '2024-01-22', 120)
END
"RETURN ( '2024-01-22' )" подозреваю неявно представляет собой CAST, а для CAST и CONVERT есть свои ограничения для детерминированности, собственно касаемо дат:
https://learn.microsoft.com/en-us/sql/relational-databases/user-defined-functions/deterministic-and-nondeterministic-functions?view=sql-server-ver16
CAST Deterministic unless used with datetime, smalldatetime, or sql_variant.
CONVERT Deterministic unless one of these conditions exists:
Source type is sql_variant.
Target type is sql_variant and its source type is nondeterministic.
Source or target type is datetime or smalldatetime, the other source or target type is a character string, and a nondeterministic style is specified. To be deterministic, the style parameter must be a constant. Additionally, styles less than or equal to 100 are nondeterministic, except for styles 20 and 21. Styles greater than 100 are deterministic, except for styles 106, 107, 109 and 113.
Как бы сделать такую скалярку детерминированной ?
CREATE OR ALTER FUNCTION dbo.func()
RETURNS DATETIME
WITH SCHEMABINDING
AS
BEGIN
RETURN ( '2024-01-22' )
END
go
SELECT OBJECTPROPERTY(OBJECT_ID('dbo.func'), 'IsDeterministic');
По ней фильтр и план сильно хуже в сравнении с фильтром по константе.