USE [Database] IF OBJECT_ID('[Functions].[product_with_barcode_stock]') IS NOT NULL DROP FUNCTION [Functions].[product_with_barcode_stock]; GO CREATE FUNCTION [Functions].[product_with_barcode_stock]( @barcode AS BIGINT ) RETURNS INT AS BEGIN DECLARE @product_inflow_sum AS INT; SET @product_inflow_sum = ( SELECT ISNULL(SUM([count]), 0) AS [sum] FROM [Tables].[product_inflow_records] WHERE [barcode] = @barcode ); DECLARE @result AS INT; WITH [counts] AS ( SELECT [POR].[count] AS [outflow_count], [PWOR].[count] AS [write_off_count] FROM [Tables].[products] AS [P] LEFT OUTER JOIN [Tables].[product_outflow_records] AS [POR] ON [POR].[barcode] = [P].[barcode] LEFT OUTER JOIN [Tables].[product_write_off_records] AS [PWOR] ON [PWOR].[barcode] = [P].[barcode] GROUP BY GROUPING SETS ( ([POR].[count]), ([PWOR].[count]) ) ) SELECT @result = ( @product_inflow_sum - ISNULL(SUM([outflow_count]), 0) - ISNULL(SUM([write_off_count]), 0) ) FROM [counts]; RETURN @result; END GO