2

Basically this is what I want to achieve. I am receiving both UserId and ProductId as parameters on my stored procedure, which inserts those values into a table called UserProduct. The ProductId is supplied as a comma separated array parameter and the UserId as a single integer value.

The following is the result set sample of what I want to achieve after select statement from this table. Is this achievable? Thanks in advance.

UserId  ProductId
-------------------
817      7 
817      5
817     33
798      6
798     12
798      2
798      4
888      5
...    ...
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
K.Paul
  • 23
  • 1
  • 5

2 Answers2

2

You can try below TSQL.

-- supposing @ProductID comma seperated values - varchar
DECLARE @ix INT
DECLARE @value varchar(25)

WHILE PATINDEX('%,%', @ProductId) <> 0 
BEGIN
     SELECT  @ix= PATINDEX('%,%',@ProductId)
     SELECT  @value= LEFT(@ProductId, @ix- 1)
     SELECT  @ProductId= STUFF(@ProductId, 1, @ix, '')

    INSERT INTO table (UserId,ProductId) VALUES(@UserId, @value)
END

In fact, you should consider taking productIDs as an array.

Fer
  • 1,962
  • 7
  • 29
  • 58
  • 2
    This is the slowest way possible to split strings. The fastest way (apart from SQLCLR) uses XML. SQL Server 2016 added STRING_SPLIT which is faster than all previous techniques – Panagiotis Kanavos Apr 19 '18 at 08:36
2

Kindly find this..

DECLARE @valueList varchar(8000)
DECLARE @pos INT
DECLARE @len INT
DECLARE @value varchar(8000)

SET @valueList = 'aa,bb,cc,f,sduygfdctys,w,e,r,t,sd sdf sdf,yyy yyy yy,'

--the value list string must end with a comma ','
--so, if the last comma it's not there, the following IF will add a trailing comma to the value list
IF @valueList NOT LIKE '%,'
BEGIN
    set @valueList = @valueList + ','
END


set @pos = 0
set @len = 0

WHILE CHARINDEX(',', @valueList, @pos+1)>0
BEGIN
    set @len = CHARINDEX(',', @valueList, @pos+1) - @pos
    set @value = SUBSTRING(@valueList, @pos, @len)
    --SELECT @pos, @len, @value /*this is here for debugging*/

    PRINT @value
    --Here is you value
    --DO YOUR STUFF HERE
    --DO YOUR STUFF HERE
    --DO YOUR STUFF HERE
    --DO YOUR STUFF HERE
    --DO YOUR STUFF HERE

    set @pos = CHARINDEX(',', @valueList, @pos+@len) +1
END
Sheriff
  • 738
  • 10
  • 20