1

I want to Make query which will set Product Name to Product NAme + Category Name where Categories can be multiple

Update P Set P.Name = ISNULL(P.Name,'')+','+ C.NAme 
from Product P
Left Outer Join Category C On P.CategoryId = C.Id.

Now one Product can have multiple categories E.g. Alpenliebe Jar product can have Multiple Categories as Toffies and Candies I want to set its Name to Alpenliebe Jar,Toffies,Candies My current query works but only setting name to Alpenliebe Jar,Toffies

Any Help

5
  • 1
    The outer join returns you data row by row & not in a single row. To update all candies with your 1st value, you must have candies data returned as a single row (comma separated). Commented Feb 3, 2014 at 6:38
  • Right, But is there any other workaround to this, like nested subqueries or something like this Commented Feb 3, 2014 at 6:41
  • I'm not really in sql querries, but I think this may help you. -> stackoverflow.com/questions/194852/… Commented Feb 3, 2014 at 6:46
  • @NitinVarpe check this link stackoverflow.com/questions/12435284/… There is a SQL function to return the data as csv. You can then call this function & concatenate these values with your candy name. Commented Feb 3, 2014 at 6:48
  • 1
    Consider string aggregation using FOR XML PATH Commented Feb 3, 2014 at 6:50

4 Answers 4

1

Try this...

UPDATE P SET P.Name = P.Name+'-'+ SUBSTRING((SELECT ', ' + C.NAme FROM Product P INNER  JOIN Category C ON P.CategoryId = C.Id 
        WHERE P.Name = PH.Name
        ORDER BY P.Name FOR XML PATH('')),2,200000) FROM Product PH
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:-

Update p
Set P.Name = STUFF((
                       SELECT P.Name +  ',' + IsNull(CName,'')
                       FROM Category  c
                       WHERE p.CategoryID = c.ID
                       FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from Product p

Comments

0

Try like this

DECLARE @Names VARCHAR(8000)  
SET @Names = SELECT COALESCE(@Names + ',', '') + C.Name FROM Category JOIN Product P On P.CategoryId = C.Id.

Update P Set P.Name = ISNULL(P.Name,'')+ ',' + @Names 
FROM Product P

COALESCE

2 Comments

But this will set same category name to all products
@NitinVarpe You have join know so it will have category based on Product
0
WITH cte(Id,Name) 
AS 
(

   SELECT ID, Name
   FROM Category
   WHERE [CategoryId] IS NULL  

   UNION ALL -- starts recursion

   SELECT  ID, P.Name +',' C.Name 
   FROM Category C
   JOIN cte P ON P.ID = C.[ParentId]
)

Update P Set P.Name = C.NAme + ISNULL(P.Name,'')
from Product P
Left Outer Join Category C On P.CategoryId = C.Id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.