2012-03-28 133 views
0

我想考第一這個問題的答案:需要DB2查詢轉換爲TSQL

SQL - message schema - need to find an existing message thread given a set of users

首先回答這個問題寫在DB2,我有一個困難時期將答案轉換爲TSQL。有人能幫我解決這個問題嗎?這裏的查詢:

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) 

查詢的描述是答案,這有很大幫助的一部分。查詢的第一部分創建一個名爲Selected_Users的臨時表,但我不確定這將如何完成。提前致謝!

+0

我更新了TSQL版本的原始問題。謝謝! – Redtopia 2012-03-28 23:53:49

回答

2

我不認爲T-SQL允許使用DB2的列表語法。 作爲舍甫琴科m個點了,SQL 2008+確實允許一個相當類似的語法:

WITH Selected_Users(id) AS (
    SELECT Id FROM (
     VALUES (@id1), (@id2), --etc-- 
    ) AS V(Id) 
), 
.... 

或者你可以創建一個真正的臨時表(或變量):

DECLARE @selected_Users TABLE (id int); 
INSERT @selected_Users VALUES 
(@id1), 
(@id2), 
--etc.-- 
; --make sure to close with semi-colon before WITH CTE 

然後替換Selected_Users@selected_Users在查詢的其餘部分。或更改初始CTE到:

WITH Selected_Users(id) AS (
    SELECT * FROM @selected_Users 
), 
.... 

或者,你可以做一個UNION ALL

WITH Selected_Users(id) AS (
    SELECT @id1 
    UNION ALL SELECT @id2 
    UNION ALL SELECT @id3 
    --etc.-- 
), 
.... 
+0

太棒了!這有幫助。儘管我在列名方面遇到了一些問題。 – Redtopia 2012-03-28 22:23:35

+1

在SQL Server(2008+)中,不能直接使用'VALUES(...),... ...作爲CTE中行集的定義,但可以從中選擇:SELECT * FROM(VALUES (@ id1),(@ id2),...)x(v)'。該SELECT *可以被放入CTE中。 – 2012-03-28 22:56:49

+0

@AndriyM - 太棒了!我不知道 - 更新答案.... – 2012-03-29 13:55:00

1

我不熟悉DB2,但是如果Selected_Users和Threads「臨時表」應該是CTE(常用表表達式 - 基本上是內聯視圖),那麼您必須將其更改爲:

WITH Selected_Users(id) AS 
(
    SELECT @id1 UNION 
    SELECT @id2 
), 
Threads(id) AS 
(
    SELECT DISTINCT 
     threadFk 
    FROM 
     ThreadMembers a 
    JOIN 
     Selected_Users b 
     ON 
     a.userFk = b.id 
) 
SELECT 
    a.Id 
FROM 
    Threads a 
WHERE 
... 

我會考慮其餘的,並儘快更新。