Northwind Database (Document! X Sample)
AdventureWorks Database / dbo Schema / dbo.ufnGetProductDealerPrice User Defined Function
In This Topic
    dbo.ufnGetProductDealerPrice User Defined Function
    In This Topic
    Description
    Scalar function returning the dealer price for a given product on a particular order date.
    Properties
    Creation Date27/10/2017 14:33
    Encrypted
    Ansi Nulls
    Parameters
    ParameterDirectionDescriptionData TypeSize
    InInput parameter for the scalar function ufnGetProductDealerPrice. Enter a valid ProductID from the Production.Product table.Integer4
    InInput parameter for the scalar function ufnGetProductDealerPrice. Enter a valid order date.DBTimeStamp4
    Return Value Currency8
    Objects that dbo.ufnGetProductDealerPrice depends on
     Database ObjectObject TypeDescriptionDep Level
    dbo.Flag datatypedbo.FlagUser Defined Data Type 4
    dbo.Name datatypedbo.NameUser Defined Data Type 2
    Production.Product tableProduction.ProductTableProducts sold or used in the manfacturing of sold products.1
    Production.ProductCategory tableProduction.ProductCategoryTableHigh-level product categorization.3
    Production.ProductListPriceHistory tableProduction.ProductListPriceHistoryTableChanges in the list price of a product over time.2
    Production.ProductModel tableProduction.ProductModelTableProduct model classification.2
    Production.ProductSubcategory tableProduction.ProductSubcategoryTableProduct subcategories. See ProductCategory table.2
    Production.UnitMeasure tableProduction.UnitMeasureTableUnit of measure lookup table.2
    Procedure Source Code
    
    
    CREATE FUNCTION [dbo].[ufnGetProductDealerPrice](@ProductID [int], @OrderDate [datetime])
    RETURNS [money] 
    AS 
    
    -- Returns the dealer price for the product on a specific date.
    BEGIN
        DECLARE @DealerPrice money;
        DECLARE @DealerDiscount money;
    
        SET @DealerDiscount = 0.60  -- 60% of list price
    
        SELECT @DealerPrice = plph.[ListPrice] * @DealerDiscount 
        FROM [Production].[Product] p 
            INNER JOIN [Production].[ProductListPriceHistory] plph 
            ON p.[ProductID] = plph.[ProductID] 
                AND p.[ProductID] = @ProductID 
                AND @OrderDate BETWEEN plph.[StartDate] AND COALESCE(plph.[EndDate], CONVERT(datetime, '99991231', 112)); -- Make sure we get all the prices!
    
        RETURN @DealerPrice;
    END;
    
    See Also