2017-05-25 28 views
0

好吧,我有以下命令獲取我的一些數據與一些訂單號。問題是,當數據集不止一個時,訂單值保持相同而不是自動遞增。如何在SQL存儲過程中有一個循環

例如:

如果我取數據逐個在表中的訂單值增量按照下面的邏輯,但是如果在一次時間爲多於一個的數據中取出的順序保持相同即它會自動遞增所有獲取相同值的行。也許某種循環,我可以在這裏獲取數據並逐一更新。幫助我在存儲過程中實現循環/數組條件。我的命令如下:

declare @MaxOrder1 int=0 

select @MaxOrder1 = max([order]) from [dbo].[XYZ_ABC_Table1] where [Id][email protected] 
if (@MaxOrder1 is null) 
begin 

set @MaxOrder1 =0 
end 
set @MaxOrder1 = @MaxOrder1+1 

UPDATE STPC SET STPC.[IsIncluded]= PT.[Value] FROM [dbo].[XYZ_ABC_Table1] STPC join @Table2 PT on (PT.Id = STPC.Id) 
    UPDATE STPC SET STPC.[Order]= case 
        when STPC.[IsIncluded] = 1 then @MaxOrder1 
        else '' 
        END 
        FROM [dbo].[XYZ_ABC_Table1] STPC join @Table2 PT on (PT.Id = STPC.Id) 

回答

0

嘗試與while while循環。

declare @MaxOrder1 int=0 

select @MaxOrder1 = max([order]) from [dbo].[XYZ_ABC_Table1] where [Id][email protected] 
if (@MaxOrder1 is null) 
begin 

set @MaxOrder1 =0 
end 
---while loop start 
WHILE (@intFlag <=5) -- replace 5 with your limit 
BEGIN 
set @MaxOrder1 = @MaxOrder1+1 

UPDATE STPC SET STPC.[IsIncluded]= PT.[Value] FROM [dbo].[XYZ_ABC_Table1] STPC join @Table2 PT on (PT.Id = STPC.Id) 
    UPDATE STPC SET STPC.[Order]= case 
        when STPC.[IsIncluded] = 1 then @MaxOrder1 
        else '' 
        END 
        FROM [dbo].[XYZ_ABC_Table1] STPC join @Table2 PT on (PT.Id = STPC.Id) 

END -- while loop end here 
+0

我上面下面讓超時錯誤代碼 –

+0

你需要更新多少行?需要您的樣本數據和確切的SP。 –

+0

樣本數據大約在4-5行......並且SP與上面相同 –

0
declare @MaxOrder1 int=0 
declare @MinOrder int=0 
select top 1 @MaxOrder1 = [order] from [dbo].[XYZ_ABC_Table1] where [Id][email protected] order by [order] 
select top 1 @MinOrder = [order] from [dbo].[XYZ_ABC_Table1] where [Id][email protected] order by [order] desc 

while(@MinOrder<>@MaxOrder1) 
BEGIN 

//rest of your code 


set @[email protected]+1 
end 

假設您的訂單是一個序列1,2,3,4,5,而不是1,3,5,7,8

+0

我在「頂部」得到不正確的語法。你能再請檢查 –

+0

我修復它再次檢查 –