函数中的SELECT语句 - 别名,临时表等

时间:2013-03-22 17:38:58

标签: sql sql-server

我正在尝试创建一个函数,用户输入日期然后接收表格。 该函数返回每天显示的表(transdate)进入的邮件类型和数量,然后生成特定于每种邮件类型的运行总计。它作为一个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 

1 个答案:

答案 0 :(得分: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