0
votes

I have two tables orders and company. Company table contains unique company id and company name.

Orders table has two column, one is orderid and other is companyIDs. CompanyIds can be multiple comma separated values.

I am using following query to get the company name corresponding to each company id of orders table.

SELECT 
    (SELECT GROUP_CONCAT(cmp.cmpny_name) 
    FROM company cmp 
    WHERE FIND_IN_SET(cmp.CompanyID, odr.companyIDs) 
    ) AS company
FROM orders odr

It works perfectly fine in Mysql but not in sql server as these keywords are not supported in sql server and I haven' worked on sql server much so please help me to find correct way to accomplish this.

Thanks

On search, I have got some keywords like stuff for group concat but not able to use properly. Not able to find an equivalent of the find_in_set for sql server.

SELECT 
    (SELECT GROUP_CONCAT(cmp.cmpny_name) 
    FROM company cmp 
    WHERE FIND_IN_SET(cmp.CompanyID, odr.companyIDs) 
    ) AS company
FROM orders odr

Not working in sql server

2
The SQL Server eqivilent of GROUP_CONCAT would be STRING_AGG. As the the latter, depends on the requirement.Larnu

2 Answers

0
votes

GroupConcat can be replaced by STRING_AGG() and you can replace also Find_In_Set by CONCAT(',',yourVariable,',') LIKE CONCAT('%,',youOtherVariable,',%')

So I think this might help you

SELECT 
    (SELECT STRING_AGG(cmp.cmpny_name,',') 
    FROM company cmp 
    WHERE CONCAT(',',cmp.CompanyID,',') LIKE CONCAT('%,',odr.companyIDs,',%') 
    ) AS company
FROM orders odr

Ref:

FIND_IN_SET() equivalent in SQL Server

https://database.guide/the-sql-server-equivalent-to-group_concat/

0
votes

This should work with SQL server 2016, if its lower split function should be written in a different way

        SELECT 
          STUFF(  ( 
            SELECT ',' + cmp.cmpny_name
            FROM company cmp 
            WHERE cmp.CompanyID IN (SELECT value FROM STRING_SPLIT (odr.companyIDs,','))
           FOR XML PATH('')), 1, 1, NULL)  AS company
        FROM orders odr

if SQL server 2017

        SELECT 
            (SELECT STRING_AGG(cmp.cmpny_name) 
            FROM company cmp 
            WHERE cmp.CompanyID in (SELECT value FROM string_split (odr.companyIDs,','))
            ) AS company
        FROM orders odr