Here is the script; I have a list of CustomerIds (1, 2, 3) that are associated with OrderIds. I have one stored procedure Delete_OrdersByCustomerIdsthat deletes all orders associated with the specified CustomerIds.
Currently, the way I do this is to combine CustomerIds into a string, that is, "1,2,3". Then I pass this line to my stored procedure and use the following function to create an Int table that I can join:
CREATE FUNCTION [dbo].[iter$simple_intlist_to_tbl] (@list nvarchar(MAX))
RETURNS @tbl TABLE (number int NOT NULL) AS
BEGIN
DECLARE @pos int,
@nextpos int,
@valuelen int
SELECT @pos = 0, @nextpos = 1
WHILE @nextpos > 0
BEGIN
SELECT @nextpos = charindex(',', @list, @pos + 1)
SELECT @valuelen = CASE WHEN @nextpos > 0
THEN @nextpos
ELSE len(@list) + 1
END - @pos - 1
INSERT @tbl (number)
VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
SELECT @pos = @nextpos
END
RETURN
END
Then I just do it DELETE FROM Orders WHERE CustomerId IN iter$simple_intlist_to_tbl(@CustomerIds).number. (The syntax may not be here, I think out loud.)
, . ? SQL, .Net ADO-.
, , , , SQL 2005?