用户定义的函数和CASE语句

时间:2014-10-10 06:38:41

标签: sql-server tsql case stored-functions

我是SQL Server的新手。在这里,我尝试使用CASE语句创建UDF,以根据输入的各种订单日期从数据库STRDAT获取订单状态。 这是代码:

USE STRDAT
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF OBJECT_ID(N'dbo.GetOrderStatus', N'FN') IS NOT NULL
    DROP FUNCTION dbo.GetOrderStatus ;
GO

CREATE FUNCTION dbo.GetOrderStatus(@lngOrderID int)
RETURNS varchar(50)
AS
BEGIN
    WITH MyData AS  
        (
        SELECT 
            ReservedDate AS Res,
            ConfirmedDate AS Conf,
            ProcessedDate AS Procs,
            ProducedDate AS Prod,
            ShippedDate AS Ship,
            RefusingReason AS Refs,
            CancelledDate AS Canc
        FROM tbl_Order 
        WHERE OrderID = @lngOrderID
        )

        SELECT GetOrderStatus= CASE
            WHEN res IS NULL AND conf IS NULL AND PROCS IS NULL AND PROD IS NULL AND Ship IS NULL AND Canc IS NULL AND Refs is null
            THEN 'Naujas'

            WHEN NOT Canc IS NULL
            THEN 'Atšauktas'

            WHEN NOT Refs IS NULL
            THEN 'Atmestas'

            WHEN NOT Ship IS NULL
            THEN 'Atkrautas'

            WHEN NOT prod IS NULL
            THEN 'Pagamintas'

            WHEN NOT Procs IS NULL
            THEN 'Apdirbtas'        

            WHEN NOT Conf IS NULL
            THEN 'Patvirtintas'

            ELSE 'N/A'
            END
        FROM MyData     
    END

这是我的第一个功能之一,我无法澄清为什么我会在CREATE FUNTION ...上遇到错误:

  

函数中包含的Select语句无法将数据返回给客户端。

2 个答案:

答案 0 :(得分:4)

你在函数结尾处缺少return语句。

并执行此操作

declare @GetOrderStatus varchar(50)

set @GetOrderStatus  = (select CASE
            WHEN res IS NULL AND conf IS NULL AND PROCS IS NULL AND PROD IS NULL 
            AND Ship IS NULL AND Canc IS NULL AND Refs is null
            THEN 'Naujas'

             WHEN NOT Canc IS NULL
             THEN 'Atšauktas'

             WHEN NOT Refs IS NULL
             THEN 'Atmestas'

             WHEN NOT Ship IS NULL
             THEN 'Atkrautas'

             WHEN NOT prod IS NULL
             THEN 'Pagamintas'

             WHEN NOT Procs IS NULL
             THEN 'Apdirbtas'        

             WHEN NOT Conf IS NULL
             THEN 'Patvirtintas'

        ELSE 'N/A'
        END
    FROM MyData 
   return @GetOrderStatus 

答案 1 :(得分:1)

  1. 添加RETURN关键字
  2. 用括号括起查询
  3. 删除GetOrderStatus=
  4. 试试这个:

    RETURN (WITH MyData AS
          ...
          SELECT CASE
          ...
          FROM mydata);
    

    BTW:

    WHEN res IS NULL AND conf IS NULL AND PROCS IS NULL AND PROD IS NULL AND Ship IS NULL AND Canc IS NULL AND Refs is null
    

    可以更优雅地表达为:

    WHEN COALESCE(res, conf, PROCS, PROD, Ship, Canc, Refs) IS NULL