2012-09-26 54 views
5

其實我已經在sql server 2008中創建了一個用戶定義的表類型。結構如下。如何使一個函數,使用用戶定義的表類型作爲參數,並返回相同的SQL?

我傳遞它作爲參數在函數中,該函數也返回該類型的表類型。我面臨的問題,而我在函數中聲明該類型的變量,插入一些數據並返回該參數。

表型結構爲:

Create Type OfferWithSubscription as Table           
    (          
    OfferID int, 
    OfferUserID int,          
    OfferImage varchar(200),       
    OfferExactPrice Decimal(18,2),         
    OfferContent varchar(max), 
    OfferTitle varchar(100),          
    StartDate datetime,          
    EndDate datetime,          
    StartTime datetime,          
    StopTime datetime,        
    ShowToUser bit,  
    SubID int,      
    SubLevel varchar(100) 
    ) 

和作用,我想創建是:

CREATE FUNCTION FN_ShowOffer 
( 
    @Gold int, 
    @Silver int, 
    @Bronze int, 
    @table dbo.OfferWithSubscription Readonly) 
RETURNS dbo.OfferWithSubscription 
AS 
BEGIN 

DECLARE @ReturnTable AS dbo.OfferWithSubscription; 
Declare @Case as varchar(20) 
     if(@Gold=0 and @Silver=1 and @Bronze=0) 
      begin 
      set @Case='1S' 
      end 
      if(@Case='1S') 
      Begin 
        insert into @ReturnTable          
        select OfferID, OfferUserID, OfferImage, 
        OfferExactPrice, OfferContent, 
        OfferTitle, StartDate, EndDate, 
        StartTime, StopTime, ShowToUser, 
        SubID, SubLevel 
        from @table 
        where SubID=4 
      End 

RETURN (

@ReturnTable 
) 
END 

回答

4

你只需要拓展型像下面。
FYI - Can T-SQL function return user-defined table type?

CREATE FUNCTION FN_ShowOffer 
( 
    @Gold int, 
    @Silver int, 
    @Bronze int, 
    @table dbo.OfferWithSubscription Readonly) 
RETURNS @ReturnTable Table           
    (          
    OfferID int, 
    OfferUserID int,          
    OfferImage varchar(200),       
    OfferExactPrice Decimal(18,2),         
    OfferContent varchar(max), 
    OfferTitle varchar(100),          
    StartDate datetime,          
    EndDate datetime,          
    StartTime datetime,          
    StopTime datetime,        
    ShowToUser bit,  
    SubID int,      
    SubLevel varchar(100) 
    ) 
AS 
BEGIN 
Declare @Case as varchar(20) 
     if(@Gold=0 and @Silver=1 and @Bronze=0) 
      begin 
      set @Case='1S' 
      end 
      if(@Case='1S') 
      Begin 
      insert into @ReturnTable          
      select OfferID,OfferUserID,OfferImage,OfferExactPrice,OfferContent,OfferTitle, 
      StartDate,EndDate,StartTime,StopTime,ShowToUser,SubID,SubLevel from @table where SubID=4 
      End 

RETURN 
END 

爲了進一步澄清,這是完全兼容,並且分配給該表類型的變量,例如SQL Fiddle

declare @t OfferWithSubscription 
insert @t 
select * from fn_showoffer(1,2,3,@t) 
+0

理查德先生,非常感謝您的快速回復。 它對我很有幫助。 –

+0

Mahmoud Gamal先生,它顯示錯誤 「必須聲明標量變量」@ReturnTable「。」 –

+0

您是否錯過函數頭中的'RETURNS @ReturnTable Table'行? – RichardTheKiwi

相關問題