2013-03-22 60 views
0

我想創建一個函數,其中用戶輸入一個日期,然後收到一個表。 函數返回每天顯示的表格(transdate)什麼類型的郵件進來以及有多少,然後生成特定於每種郵件類型的運行總數。它作爲select語句正常工作,但是當我嘗試並將函數格式放入時,我收到錯誤: 「Select函數中包含的Select語句無法將數據返回給客戶端。」函數內的SELECT語句 - 別名,與臨時表...等

CREATE FUNCTION DailyMailCount(@Date datetime) 
RETURNS @Count TABLE 
        (
    [ID] int identity (1,1), 
    Transdate datetime, 
    Donation varchar (10), 
    DailyCount int, 
    RunningTotal int  
        ) 

AS 
BEGIN 

DECLARE @running_total TABLE (Transdate DATETIME,Donation varchar(30), countz INT,row int) 
INSERT INTO @running_total 

SELECT TransDate,Donation, COUNT(*) 
,ROW_number() OVER (PARTITION BY Donation order by TransDate ASC) as row 
FROM RevInt.DetailDonation WHERE TransDate > '@Date' GROUP BY TransDate,Donation 

SELECT 
r1.Transdate, 
r1.Donation, 
r1.countz, 
SUM(r2.countz) as running_total 
FROM @running_total r1 
LEFT OUTER JOIN @running_total r2 on r2.donation = r1.Donation 
       AND r2.row <= r1.row 
GROUP BY 
r1.transdate, 
r1.countz, 
r1.donation, 
r1.row 
ORDER BY r1.Donation 

     RETURN 
END 
+0

這看起來像一個存儲過程,而不是一個函數。 – 2013-03-22 17:41:49

+0

我是新來的函數和存儲過程。你能簡單地向我解釋爲什麼這應該是一個SP? – user2200270 2013-03-22 17:55:12

回答

1

正確的語法是:

CREATE FUNCTION DailyMailCount(@Date datetime) 
RETURNS @Count TABLE (
    [ID] int identity (1,1), 
    Transdate datetime, 
    Donation varchar (10), 
    DailyCount int, 
    RunningTotal int  
) 
as begin 
    DECLARE @running_total TABLE (Transdate DATETIME,Donation varchar(30), countz INT,row int) 
    INSERT INTO @running_total 
     SELECT TransDate,Donation, COUNT(*), 
       ROW_number() OVER (PARTITION BY Donation order by TransDate ASC) as row 
     FROM DetailDonation 
     WHERE TransDate > '@Date' 
     GROUP BY TransDate, Donation; 

    insert into @Count 
     SELECT r1.Transdate, r1.Donation, r1.countz, 
       SUM(r2.countz) as running_total 
     FROM @running_total r1 
      LEFT OUTER JOIN @running_total r2 
      on r2.donation = r1.Donation AND r2.row <= r1.row 
     GROUP BY r1.transdate, r1.countz, r1.donation, r1.row 
     ORDER BY r1.Donation; 

    RETURN; 
END; 

你缺少insert到返回表。

您還可以創建一個在線功能(一個語句)通過使用一個單一的查詢:

return with running_total as (
    SELECT TransDate,Donation, COUNT(*), 
      ROW_number() OVER (PARTITION BY Donation order by TransDate ASC) as row 
    FROM RevInt.DetailDonation 
    WHERE TransDate > '@Date' 
    GROUP BY TransDate,Donation 
) 
SELECT r1.Transdate, r1.Donation, r1.countz, SUM(r2.countz) as running_total 
FROM running_total r1 LEFT OUTER JOIN 
    running_total r2 
    on r2.donation = r1.Donation 
       AND r2.row <= r1.row 
GROUP BY r1.transdate, r1.countz, r1.donation, r1.row 
ORDER BY r1.Donation 
+0

謝謝,我會試一試 – user2200270 2013-03-22 17:59:49

+0

我不確定我是否正在跟隨你。您介意複製並粘貼我的原始代碼發佈並向我展示如何更改它? – user2200270 2013-03-22 18:10:39

+0

@ user2200270。 。 。我修好了它。我原來的回答只是錯誤的方向。 – 2013-03-22 18:18:03