-1

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

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

如何在存储过程中加入结果表?

4

3 回答 3

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
于 2012-08-10T05:25:25.023 回答
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

看到这个小提琴。
从同一个表中选择数据的其他方法是:

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'

看到这个小提琴

于 2012-08-10T09:54:44.693 回答
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'
于 2012-08-10T06:04:21.860 回答