如果Else语句在Table Valued函数中

时间:2017-07-22 16:30:38

标签: sql-server

我有一张桌子

ProdID, ProdName, Price

我想在表值函数中使用if else语句使得如果Qty大于或等于10,我会给出10%的折扣,否则没有折扣。这是我的代码。

Create function FDiscount (@ProdName varchar(50), @Qty int)
Returns Table
as
return 
    IF (@Qty >= 10)
        Select ProdName, Price, @Qty as Qty, Price * @Qty as Total, 
        (Price * @Qty) - (Price * @Qty) /100 * 10 as Discount10
        from TblProduct
    Else
        Select ProdName, Price, @Qty as Qty, Price * @Qty as Total
        from TblProduct
 Where ProdName = @ProdName
 select * from FDiscount('Milk','10')

但它说“关键字'IF'附近的语法不正确,我似乎无法找到任何解决方案。

3 个答案:

答案 0 :(得分:1)

为什么不是一个简单的CASE语句

CREATE FUNCTION Fdiscount (@ProdName VARCHAR(50), 
                           @Qty      INT) 
returns TABLE 
AS 
    RETURN 
      (SELECT prodname, 
              price, 
              @Qty         AS Qty, 
              price * @Qty AS Total, 
              CASE 
                WHEN @Qty >= 10 THEN ( price * @Qty ) - ( price * @Qty ) / 100 * 10 
                ELSE 0 
              END          AS Discount10 
       FROM   tblproduct 
       WHERE  prodname = @ProdName) 

答案 1 :(得分:0)

您可以阅读此https://stackoverflow.com/questions/440308/tsql-returning-a-table-from-a-function-or-store-procedure

并使用此

Create function FDiscount (@ProdName varchar(50), @Qty int)
Returns @retTbl Table(ProdName VARCHAR(100), Price INT, Qty INT, Discount10 INT)
as
BEGIN
DECLARE @tbl TABLE (ProdName VARCHAR(100), Price INT, Qty INT, Discount10 INT)
    IF @Qty >= 10
         INSERT INTO @tbl
         Select ProdName, Price, @Qty , Price * @Qty, 
        (Price * @Qty) - (Price * @Qty) /100 * 10   
        from TblProduct
    Else
        INSERT INTO @tbl
         Select ProdName, Price, @Qty , Price * @Qty , 0
        from TblProduct
 Where ProdName = @ProdName
 return
END 

答案 2 :(得分:0)

两件事......#1无论提供什么参数值,函数都必须返回相同数量的列。因此,您无法在&amp ;;上切换折扣列。以@Qty为基础。 #2多语句功能(mTVF)往往表现得非常糟糕。您应该尝试使您的功能成为内联功能(iTVF)。 请参阅以下内容作为建议的重写...

CREATE FUNCTION dbo.FDiscount (@ProdName varchar(50), @Qty int)
RETURNS TABLE WITH SCHEMABINDING AS
RETURN 
    SELECT 
        p.ProdName, 
        p.Price, 
        Qty = @Qty,
        Total = p.Price * @Qty,
        Discount10 = IIF(@Qty >= 10, (p.Price * @Qty) - (p.Price * @Qty) / 100 * 10, 0)
    FROM 
        dbo.TblProduct p
    WHERE 
        p.ProdName = @ProdName;
GO

HTH, 杰森