FIND_IN_SET() equivalent in SQL Server

2020-02-14 05:25发布

问题:

SELECT * FROM users WHERE uid IN (SELECT doctors FROM MainPage WHERE Valid=1)

users table uid INT
Mainpage table doctors text with value as 1,2,3,4,5

When I am running the above query, it is only resulting 1 row which is for uid = 1, however I wanted all the 5 rows. So in MySQL I used this query:

SELECT *
FROM users
JOIN MainPage ON FIND_IN_SET(uid, doctors)
WHERE Valid = 1;

It worked. I am trying to find an equivalent in SQL Server for FIND_IN_SET to achieve the same result ?

回答1:

This might work

SELECT *
FROM users u
WHERE EXISTS (
    SELECT *
    FROM MainPage
    WHERE CONCAT(',',doctors,',') LIKE CONCAT('%,',u.uid,',%')
        AND Valid = 1
)


回答2:

Since SQL Server 2016 (13.x) there is STRING_SPLIT()

SELECT *
FROM users
WHERE uid IN
 (SELECT value FROM STRING_SPLIT(
     (SELECT doctors FROM MainPage WHERE Valid = 1),
     ','))