如何遍历ID列表

时间:2016-02-11 18:34:02

标签: sql-server tsql

我在select语句中获得了id列表。如何遍历每个ID并在下面打印

DECLARE @InventoryID INT
Select @InventoryID = I.InventoryID
From G2owner.LoadSlip L (nolock)
     Inner Join G2owner.LoadSlipReleaseOrderMapping LM (nolock) on L.LoadSlipID = LM.LoadSlipID
     Inner Join G2owner.LoadSlipDetail LSD (nolock) on LM.LoadSlipReleaseOrdermappingID = LSD.LoadSlipReleaseOrdermappingID 
     Inner Join G2owner.Inventory I (nolock) on LSD.InventoryID = I.InventoryID
Where LM.ReleaseOrderID = 7156 and L.LoadSlipID = 3014
      and L.TerminalID = 3 and I.InventoryEndDate IS NULL and I.TotalNetWeight = 0.0000000

PRINT @InventoryID

1 个答案:

答案 0 :(得分:1)

避免使用游标或任何逐行操作,如果可以的话,它会使用循环,因为它会影响性能,但是如果你不得不这样做:

DECLARE @InventoryID INT

DECLARE myCursor CURSOR FOR 
SELECT I.InventoryID
From G2owner.LoadSlip L with(nolock)
    Inner Join G2owner.LoadSlipReleaseOrderMapping LM with(nolock) on L.LoadSlipID = LM.LoadSlipID
    Inner Join G2owner.LoadSlipDetail LSD with(nolock) on LM.LoadSlipReleaseOrdermappingID = LSD.LoadSlipReleaseOrdermappingID 
    Inner Join G2owner.Inventory I with(nolock) on LSD.InventoryID = I.InventoryID
Where LM.ReleaseOrderID = 7156 and L.LoadSlipID = 3014
    and L.TerminalID = 3 and I.InventoryEndDate IS NULL and I.TotalNetWeight = 0.0000000

OPEN myCursor
FETCH NEXT FROM myCursor INTO @InventoryID 

WHILE @@FETCH_STATUS = 0
BEGIN

    PRINT (@InventoryID);
   FETCH NEXT FROM myCursor INTO @InventoryID
END
CLOSE myCursor
DEALLOCATE myCursor

同样WITH(nolock)会导致脏读!!!