Microsoft SQL Server Natively compiled scalar function


Example

Code in natively compiled function will be transformed into C code and compiled as dll. To create a Native Compiled scalar function you need to:

  • Use standard CREATE FUNCTION syntax
  • Set NATIVE_COMPILATION option in function definition
  • Use SCHEMABINDING option in function definition

Instead of standard BEGIN END block, you need to use BEGIN ATOMIC block:

BEGIN ATOMIC
   WITH (TRANSACTION ISOLATION LEVEL=SNAPSHOT, LANGUAGE='us_english')
   -- T-Sql code goes here
END

Example:

CREATE FUNCTION [dbo].[udfMultiply]( @v1 int, @v2 int )   
RETURNS bigint 
WITH NATIVE_COMPILATION, SCHEMABINDING  
AS   
BEGIN ATOMIC WITH (TRANSACTION ISOLATION LEVEL = SNAPSHOT, LANGUAGE = N'English')  
  
    DECLARE @ReturnValue bigint;  
    SET @ReturnValue = @v1 * @v2;         
  
    RETURN (@ReturnValue);    
END 

-- usage sample:
SELECT dbo.udfMultiply(10, 12)