如何使我的SQL标量函数具有确定性并在其中包含可变的默认值

时间:2018-08-01 16:08:14

标签: sql-server

--DROP FUNCTION fn_NonDeterministic;
--DROP FUNCTION fn_Deterministic

CREATE FUNCTION [dbo].[fn_NonDeterministic]()
RETURNS DECIMAL (13,3)
WITH SCHEMABINDING
AS
BEGIN
    DECLARE @date AS DATETIME = '01/01/1900';
    RETURN 10.2
END
GO


SELECT ROUTINE_NAME,
       IS_DETERMINISTIC
FROM   INFORMATION_SCHEMA.ROUTINES
WHERE  ROUTINE_NAME = 'fn_NonDeterministic'
GO

CREATE FUNCTION [dbo].[fn_Deterministic]()
RETURNS DECIMAL (13,3)
WITH SCHEMABINDING
AS
BEGIN
    DECLARE @date AS DATETIME ;
    RETURN 10.2
END
GO


SELECT ROUTINE_NAME,
       IS_DETERMINISTIC
FROM   INFORMATION_SCHEMA.ROUTINES
WHERE  ROUTINE_NAME = 'fn_Deterministic'

1 个答案:

答案 0 :(得分:1)

我不认为它喜欢从字符串到日期的转换,这种转换是确定性的,因为它受区域设置的影响。

/*
dROP FUNCTION fn_NonDeterministic;
DROP FUNCTION fn_Deterministic
*/


CREATE FUNCTION [dbo].[fn_NonDeterministic]()
RETURNS DECIMAL (13,3)
WITH SCHEMABINDING
AS
BEGIN
    -- ********************************  this changes things ***********
    DECLARE @date AS datetime = datefromparts(1970,05,23);
    RETURN 10.2
END
GO


SELECT ROUTINE_NAME,
       IS_DETERMINISTIC
FROM   INFORMATION_SCHEMA.ROUTINES
WHERE  ROUTINE_NAME = 'fn_NonDeterministic'
GO
CREATE FUNCTION [dbo].[fn_Deterministic]()
RETURNS DECIMAL (13,3)
WITH SCHEMABINDING
AS
BEGIN
    DECLARE @date AS DATETIME ;
    RETURN 10.2
END
GO


SELECT ROUTINE_NAME,
       IS_DETERMINISTIC
FROM   INFORMATION_SCHEMA.ROUTINES
WHERE  ROUTINE_NAME = 'fn_Deterministic'