简体   繁体   中英

mysql query needs to be converted in sql server having find_in_set and group_concat keywords

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

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM