sql-servert-sqluser-defined-functionssql-server-2017change-tracking

How to use CHANGE_TRACKING_CURRENT_VERSION in a user defined function?


I am working on a project that uses Entity Framework and change tracking in SQL Server. I want to create a user defined function that returns the current version of the tracked changes in the database, so that I can use it in my queries with Entity Framework.

However, when I try to create the function, I get the following error:

Invalid use of a side-effecting operator 'change_tracking_current_version' within a function.

Is there a way to create a user defined function with it without causing an error?

Here is the code of my function:

CREATE FUNCTION dbo.GetChangeVersion()
RETURNS bigint
AS
BEGIN
DECLARE @version bigint;
SET @version = CHANGE_TRACKING_CURRENT_VERSION();
RETURN @version;
END

Solution

  • You can use the same workaround as also works for RAND().

    Create a helper view

    CREATE VIEW dbo.CHANGE_TRACKING_CURRENT_VERSION
    AS
    SELECT CHANGE_TRACKING_CURRENT_VERSION() AS CurrentVersion
    

    Then use

    CREATE FUNCTION dbo.GetChangeVersion()
    RETURNS bigint
    AS
    BEGIN
    DECLARE @version bigint;
    SET @version = (SELECT CurrentVersion FROM dbo.CHANGE_TRACKING_CURRENT_VERSION)
    RETURN @version;
    END