Link to home
Start Free TrialLog in
Avatar of ph0bia
ph0bia

asked on

Problem with T-SQL loop in a stored procedure

Hi All,

This problem has really been bugging me and I hope someone can help. I have written a stored procedure for SQL Server 2000 in T-SQL that searches through codes in sequence until it finds an empty code and then inserts the new record.

I am using a WHILE @ IS NOT NULL loop but the code doesn't jump out of the loop when the variable is NULL

I will post the important bits of my code below.

CREATE PROCEDURE ShipItems (@OrderID as int) AS
DECLARE @OrderCode as nvarchar(14), @i as int, @ID2 as int

SELECT @OrderCode = Code FROM [Order] WHERE ID = @OrderID
SET @i = 1
SELECT @ID2 = ID FROM Shipment WHERE Code = @OrderCode + '-1'
WHILE @ID2 is not null
BEGIN
     SET @i = @i + 1
     SELECT @ID2 = ID FROM Shipment WHERE Code = @OrderCode + '-' + CAST(@i AS nvarchar(2))
END

INSERT INTO Shipment VALUES (@OrderCode + '-' + CAST(@i AS nvarchar(2)), NULL, 0, @OrderID, 1)
GO

Any help with this would be much appreciated as I don't understand why it isn't working 'cos I have used loops like this before without any problems.

TIA,
Ph0bia
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ph0bia
ph0bia

ASKER

Thanks a lot, I'll try that and let you know :-)
Avatar of ph0bia

ASKER

Thanks angelIII you're a star... it worked perfectly. I never knew that it did that.