2017-01-02 52 views
0

我有一些「太多代碼生成」或不是最優雅的編碼方式發出了挑戰:最好在創建SQL函數的動態條件下的方式

ALTER FUNCTION [dbo].fn_Function 
    (@Location NVARCHAR(30) ='ALL') 
RETURNS @ReportTable TABLE(DateOfProviValidity date, 
          DateOfFixumValidity date, 
          UserID NVARCHAR(50) 
         ) 
AS 
BEGIN 
    DECLARE @CurrentMonth DATE 

    SET @CurrentMonth = dbo.fn_getFirstOfMonth(getdate()) 

    IF @Location IS NOT NULL AND @Location <> 'ALL' 
     INSERT INTO @ReportTable 
      SELECT * 
      FROM dbo.fn_getFinalPData(@CurrentMonth) 
      WHERE 1 AND Location = @Location 
    ELSE 
     INSERT INTO @ReportTable 
      SELECT * 
      FROM dbo.fn_getFinalPData(@CurrentMonth) 
      WHERE 1 AND Location IS NOT NULL 

    RETURN 
END 

有擺脫最初IF @Location的可能性聲明並將其更加緊密地添加到Where子句中?

我的問題是case語句不起作用,因爲我無法執行Location equals或IS NOT NULL語句。

回答

0

試試這個,

SELECT * 
FROM dbo.fn_getFinalPData(@CurrentMonth) 
WHERE 1 
    AND Location = ISNULL(NULLIF(@Location,'ALL'),Location) 
1

這樣的事情呢?

INSERT INTO @ReportTable 
SELECT * 
FROM dbo.fn_getFinalPData(@CurrentMonth) 
WHERE ISNULL(@Location, 'ALL') <> 'ALL' 
OR Location = @Location 
相關問題