I’m trying to test the first answer to this question:
SQL – message schema – need to find an existing message thread given a set of users
The first answer to this question is written in DB2 and I’m having a hard time converting the answer to TSQL. Can someone help me figure this out? Here’s the query:
WITH Selected_Users(id) as (VALUES (@id1), (@id2), --etc--),
Threads(id) as (SELECT DISTINCT threadFk
FROM ThreadMembers as a
JOIN Selected_Users as b
ON b.id = a.userFk)
SELECT a.id
FROM Threads as a
WHERE NOT EXISTS (SELECT '1'
FROM ThreadMembers as b
LEFT JOIN Selected_Users as c
ON c.id = b.userFk
WHERE c.id IS NULL
AND b.threadFk = a.id)
AND NOT EXISTS (SELECT '1'
FROM Selected_Users as b
LEFT JOIN ThreadMembers as c
ON c.userFk = b.id
AND c.threadFk = a.id
WHERE c.userFk IS NULL)
The description of the query is part of the answer, which helps a lot. The first part of the query creates a temp table called Selected_Users, but I’m not sure how this would be done. Thanks in advance!
I don’t think T-SQL allows for the list syntax that DB2 does.As Andriy M points out, SQL 2008+ does allow a pretty similar syntax:
Or you could create a real temp table (or variable):
and then replace
Selected_Userswith@selected_Usersin the rest of the query. Or change the initial CTE to:Or, you could do a
UNION ALL: