在sql server存储过程中循环select语句

时间:2014-06-17 05:40:24

标签: sql sql-server stored-procedures

我创建了一个如下所示的商店程序

    CREATE PROCEDURE [dbo].[sp_rptlabelPrint] --'HKOHBLAE11/0007'  ,'','HKO'  
    (                                                          
    @Code varchar(25),
    @Format int=0  ,
    @Branch varchar(25)=''
    )                                                          
    AS                                                        

    SELECT 

       HB.HB_cCode as HBCode,
       HB.MB_cCode as MBCode,
       PO.PO_cShortName as Dest,
       PS.PO_cShortName as Source
    FROM 
    SHI_HOUSEBLHDR HB
    left join SHI_PORTS PO on HB.PO_cDischargePortCode = PO.PO_cCode 
    left join SHI_PORTS PS on HB.PO_cLoadPortCode = PS.PO_cCode 

   where   HB.HB_cCode=@Code and HB.br_ccode=@Branch

这里重新出现一行。 但我需要将一个整数值传递给参数@Format,如果它设置为2,则select语句必须执行2次并返回两行。如果它设置为4,则返回同一行的4倍。是否可以循环select语句并返回行

2 个答案:

答案 0 :(得分:0)

写为:

CREATE PROCEDURE [dbo].[sp_rptlabelPrint] --'HKOHBLAE11/0007'  ,'','HKO'  
    (                                                          
    @Code varchar(25),
    @Format int=0  ,
    @Branch varchar(25)=''
    )                                                          
    AS                                                        

    SELECT 
       HB_cCode as HBCode,
       MB_cCode as MBCode,
       PO_cShortName as Dest,
       PO_cShortName as Source
    FROM
    (
    SELECT 
       HB.HB_cCode as HBCode,
       HB.MB_cCode as MBCode,
       PO.PO_cShortName as Dest,
       PS.PO_cShortName as Source
    FROM 
    SHI_HOUSEBLHDR HB
    left join SHI_PORTS PO on HB.PO_cDischargePortCode = PO.PO_cCode 
    left join SHI_PORTS PS on HB.PO_cLoadPortCode = PS.PO_cCode     
    where   HB.HB_cCode=@Code and HB.br_ccode=@Branch
    )T
     Cross JOIN
    (
     SELECT TOP ( @Format ) ROW_NUMBER() 
      OVER (ORDER BY s1.[object_id])
      FROM sys.all_objects AS s1
      CROSS JOIN sys.all_objects AS s2
     ) AS x(n) ;

答案 1 :(得分:0)

您可以使用临时表来存储和返回结果

ALTER PROCEDURE [dbo].[sp_rptlabelPrint] 
(                                                          
@Code varchar(25),
@Format int=0  ,
@Branch varchar(25)=''
)                                                          
AS    
CREATE TABLE #MyTempTable(HBCode VARCHAR(25),MBCode VARCHAR(25),Dest VARCHAR(25),Source VARCHAR(25))                                                    
WHILE (@Format < 4)
BEGIN

insert  INTO #MyTempTable
SELECT 

   HB.HB_cCode as HBCode,
   HB.MB_cCode as MBCode,
   PO.PO_cShortName as Dest,
   PS.PO_cShortName as Source
FROM 
SHI_HOUSEBLHDR HB
left join SHI_PORTS PO on HB.PO_cDischargePortCode = PO.PO_cCode 
left join SHI_PORTS PS on HB.PO_cLoadPortCode = PS.PO_cCode 

where   HB.HB_cCode=@Code and HB.br_ccode=@Branch


    Set @Format = @Format + 1
END
SELECT * FROM #MyTempTable