USE [Database]

IF OBJECT_ID('[Procedures].[select_expired_products]', 'P') IS NOT NULL
  DROP PROCEDURE [Procedures].[select_expired_products];
GO
CREATE PROCEDURE [Procedures].[select_expired_products]
  @date_of_manufacture_attribute_id AS INT ,
  @expiration_date_attribute_id     AS INT ,
  @actual_date                      AS DATE 
AS
WITH [values] AS (
    SELECT [p].[id], [pa].[attribute_id], [pv].[value] 
    FROM [Tables].[products] AS [p]
    JOIN [Tables].[product_attributes] AS [pa]
    ON [pa].[product_id] = [p].[id]
    JOIN [Tables].[product_values] AS [pv]
    ON [pv].[attribute_id] = [pa].[attribute_id]
       AND [pv].[product_id] = [pa].[product_id]
    WHERE [pa].[attribute_id] IN (@date_of_manufacture_attribute_id, @expiration_date_attribute_id)
)
SELECT [date_of_manufacture_attributes].[id]
FROM [values] AS date_of_manufacture_attributes
JOIN [values] AS expiration_date_attributes
  ON [expiration_date_attributes].[id] = [date_of_manufacture_attributes].[id]
     AND [expiration_date_attributes].[attribute_id] = @expiration_date_attribute_id
WHERE [date_of_manufacture_attributes].[attribute_id] = @date_of_manufacture_attribute_id
      AND DATEADD(
          DAY, CAST([expiration_date_attributes].[value] AS INT),
        CAST([date_of_manufacture_attributes].[value] AS DATE)
        ) < @actual_date;
GO