如何在SQL Server中声明表?

时间:2013-06-27 17:34:29

标签: sql-server-2008

我正在尝试创建一个需要返回表的函数,但即使是函数也没有,我需要返回结果表。

我的脚本就像这样

create function FNC_getPackageListById(@PkId int )
returns table
as
      return
        if exists (select Date1, Date2 from PromotionPackage 
                   where PkId = @PkId and Date1 is null and Date2 is null)
        begin
            select Rate,Remarks,PackageName from Package where PkId=@PkId
        end
        else
        begin
            select p.Rate,
                   p.Remarks,
                   p.PackageName,
                   pp.Date1,
                   pp.Date2
             from PromotionPackage pp,
                 Package p 
             where pp.PkId=p.PkId and  p.PkId=@PkId
       end 
   end

1 个答案:

答案 0 :(得分:1)

函数调用表值函数返回表。见这个例子:

CREATE FUNCTION TrackingItemsModified(@minId int)
RETURNS @trackingItems TABLE (
   Id       int      NOT NULL,
   Issued   date     NOT NULL,
   Category int      NOT NULL,
   Modified datetime NULL
) 
AS
BEGIN
   INSERT INTO @trackingItems (Id, Issued, Category)
   SELECT ti.Id, ti.Issued, ti.Category 
   FROM   TrackingItem ti
   WHERE  ti.Id >= @minId; 

   RETURN;
END;