2012-08-08 14 views
5

Ecco la mia query sql.Cosa posso usare al posto della tabella #Temp nella funzione sql

CREATE FUNCTION UF_GetOrderProducts 
(
    @OrderId int 
) 
RETURNS VARCHAR(500) 
AS 
BEGIN 
    SELECT Identity(int,1,1) ID, ProductId INTO #Temp FROM OrderProduct WHERE OrderId = @OrderId 

Declare @Id int, 
     @Count int, 
     @LoopCount int, 
     @ProductList VARCHAR(500), 
     @ProductListTemp VARCHAR(500) 

SET @Count = (Select Count(*) From #Temp) 

SET @LoopCount = 1 
SET @ProductList = '' 
WHILE @LoopCount <= @Count 
BEGIN 



    SET @ProductListTemp =(SELECT Name FROM Product WHERE ProductId =(Select ProductId from #Temp Where ID = @LoopCount)) 
     SET @ProductList [email protected] + '<br/>' 
     Set @[email protected] + 1   


END 
DROP TABLE #Temp 

RETURN @ProductList 

END 
GO 

Devo eseguire il ciclo nella tabella #Temp. Avete altri suggerimenti?

risposta

16

Invece della tabella temporanea è possibile utilizzare una variabile di tabella.

declare @Temp TABLE (ID int identity, ProductId int) 

insert into @Temp(ProductId) 
select ProductId 
from OrderProduct 
where OrderId = @OrderId 

Ma è possibile riscrivere la funzione senza loop.

Qualcosa di simile dovrebbe fare quello che vuoi.

create function IF_GetOrderProducts 
(
    @OrderId int 
) 
returns varchar(500) 
as 
begin 
    return 
    (
    select Name+'<br/>' 
    from Product as P 
     inner join OrderProduct as OP 
     on P.ProductId = OP.ProductId 
    where OP.OrderId = @OrderId 
    for xml path(''), type 
    ).value('.', 'varchar(500)') 
end