在存储过程中加入SQL查询结果

时间:2012-08-10 05:05:18

标签: sql sql-server-2008

我需要在存储过程中加入结果集,我尝试了这个查询,但它不正确。

SELECT * FROM (SELECT Field1, Field2 FROM Table1 WHERE Field4='val1') A
INNER JOIN 
SELECT * FROM (SELECT Field1, Field3 FROM Table1 WHERE Field4='val2') b
ON A.Field1 = B. Fileld1

如何在存储过程中连接结果表?

3 个答案:

答案 0 :(得分:3)

试试这个:

您不必使用SELECT * FROM两次..

SELECT * FROM 
(SELECT Field1, Field2 FROM Table1 WHERE Field4='val1') A
INNER JOIN 
(SELECT Field1, Field3 FROM Table1 WHERE Field4='val2') b
ON A.Field1 = B. Fileld1

答案 1 :(得分:2)

你正在做这样的事情(仅举例):

SELECT * FROM Table1 A 
INNER JOIN 
SELECT * FROM Table2 B 
ON A.FIELD1 = B.FIELD2

哪个错了。因为您不需要两次写SELECT * FROM。正确的是:

SELECT * FROM Table1 A 
INNER JOIN 
Table2 B 
ON A.FIELD1 = B.FIELD2

所以你的查询应该是(包括创建程序):

CREATE PROCEDURE testJoining 
AS 
    SELECT * FROM 
        (SELECT FIELD1, Field2 FROM Table1 WHERE Field4='VAL1') A
    INNER JOIN 
        (SELECT FIELD1, Field3 FROM Table1 WHERE Field4='VAL2') B
    ON A.FIELD1 = B.FIELD1
GO

See this fiddle.
从同一个表中选择数据的其他方法是:

SELECT A.Field1,A.Field2,B.Field3 FROM Table1 A 
INNER JOIN 
Table1 B 
ON A.FIELD1 = B.FIELD1
WHERE A.Field4='VAL1'
AND B.Field4='VAL2'

See this fiddle

答案 2 :(得分:1)

也许这会有所帮助

With cte_sample AS ( SELECT Field1, Field2 FROM Table1 
WHERE Field4='val1' )
SELECT Field1, Field3 FROM Table1 AS a
INNER JOIN cte_sample ON a.Field1 = cte_sample.Field1 AND
WHERE a.Field4='val2'