2014-10-10 45 views
1

我對SQL Server很新。在這裏,我嘗試使用CASE語句創建UDF,以根據輸入的各種訂單日期從數據庫STRDAT獲取訂單狀態。 下面是代碼:用戶定義的函數與CASE語句

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語句包括在一個功能無法將數據返回到客戶端。

回答

1
  1. 添加return關鍵字
  2. 裹在括號中的查詢
  3. 刪除GetOrderStatus=

試試這個:

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 
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 
+0

@litpost,如果這個解決您的問題,請你接受它作爲一個解決方案嗎? – Mukund 2014-10-10 07:14:55

+0

我會評價你的答案,但不會導致仍然有太低的評級在論壇上。不管怎樣,謝謝你! – litpost 2014-10-13 13:34:13