I've been using the following code to transfer a string of comma-separated values into SQL as a parameter value:DECLARE @userIDs nvarchar(max)DECLARE @separator CHARSET @separator = ','SET @userIDs= '5,10,15,22,32,44,57,120,156,1650,54247,'DECLARE @separator_position INTDECLARE @array_value nvarchar(max)SET @separator_position = NULLSET @array_value = NULLDECLARE @userTable TABLE(ID INT IDENTITY(1,1), userID INT)WHILE patindex('%' + @separator + '%' , @userIDs) <> 0 BEGIN SELECT @separator_position = patindex('%' + @separator + '%' , @userIDs) SELECT @array_value = LEFT(@userIDs, @separator_position - 1) INSERT INTO @userTable (userID) VALUES (@array_value) SELECT @userIDs = stuff(@userIDs, 1, @separator_position, '') ENDSELECT * FROM @userTable
This has worked fine for years, but recently I also need to pass a string of comma separated dates into SQL. I am using ISO dates separated by the pipe symbol like this:SET @dates = 2010-09-21T23:00:00|2010-09-21T23:00:00|2010-09-21T23:00:00|2010-09-21T23:00:00|'
When I run the code though, SQL (2005) throws an error:Invalid length parameter passed to the LEFT or SUBSTRING function.
Could anyone please explain to me what's causing this, and how I can amend the code to stop it happening?Thanks