以此示例查询:
INSERT INTO #QueryOutput
SELECT DISTINCT
UR2.LeftID, UR3.LeftID
FROM
UserRelations UR1
JOIN
UserRelations UR2 ON UR1.RightID = UR2.LeftID
JOIN
UserRelations UR3 ON UR2.RightID = UR3.LeftID
WHERE
(UR1.RelationID = 1)
OR (UR1.RelationID = 1 AND UR2.RelationID = 1)
AND UR1.LeftID IN (SELECT UserID FROM #QueryInput)
这是魔术行:
INSERT INTO #QueryOutput SELECT DISTINCT UR2.LeftID ,UR3.LeftID
#QueryOutput
是一个包含单个列的表,UserID
我希望在该单个列中插入UR2.LeftID
,UR3.LeftID
或尽可能多的UR*.LeftID
。怎么办呢?
由于
答案 0 :(得分:2)
如果您使用的是SQL Server 2008或更高版本,我认为最好的方法是使用cross apply和table valued constructor进行取消操作:
INSERT INTO #QueryOutput
SELECT DISTINCT upvt.LeftID
FROM UserRelations UR1
JOIN UserRelations UR2
ON UR1.RightID = UR2.LeftID
JOIN UserRelations UR3
ON UR2.RightID = UR3.LeftID
CROSS APPLY (VALUES (UR2.LeftID), (UR3.LeftID )) AS upvt (LeftID)
WHERE (UR1.RelationID = 1 )
OR (UR1.RelationID = 1 AND UR2.RelationID = 1 )
AND UR1.LeftID IN (SELECT UserID FROM #QueryInput)
答案 1 :(得分:0)
也许这就是你想要的:
INSERT INTO #QueryOutput
SELECT DISTINCT (case when n.n = 2 then UR2.LeftID
when n.n = 3 then UR3.LeftID
end)
FROM UserRelations UR1 JOIN
UserRelations UR2
ON UR1.RightID = UR2.LeftID JOIN
UserRelations UR3
ON UR2.RightID = UR3.LeftID CROSS JOIN
(select 2 as n union all select 3) n
WHERE (UR1.RelationID = 1 ) OR (UR1.RelationID = 1 AND UR2.RelationID = 1 ) AND
UR1.LeftID IN (SELECT UserID FROM #QueryInput);
答案 2 :(得分:0)
除非您尝试执行下面的UNION ALL
INSERT INTO #QueryOutput
SELECT DISTINCT UR2.LeftID FROM UserRelations UR1
JOIN UserRelations UR2 ON UR1.RightID = UR2.LeftID
JOIN UserRelations UR3 ON UR2.RightID = UR3.LeftID WHERE (UR1.RelationID = 1 )
OR (UR1.RelationID = 1 AND UR2.RelationID = 1 )
AND UR1.LeftID IN (SELECT UserID FROM #QueryInput)
UNION ALL
SELECT DISTINCT UR3.LeftID FROM UserRelations UR1
JOIN UserRelations UR2 ON UR1.RightID = UR2.LeftID
JOIN UserRelations UR3 ON UR2.RightID = UR3.LeftID WHERE (UR1.RelationID = 1 )
OR (UR1.RelationID = 1 AND UR2.RelationID = 1 )
AND UR1.LeftID IN (SELECT UserID FROM #QueryInput)