You are on page 1of 2

sql server 2008 - Join SQL query results inside stored procedure - Stack ...

1 de 2

http://stackoverflow.com/questions/11895767/join-sql-query-results-insid...

Join SQL query results inside stored procedure

I need to join result sets inside a stored procedure, I tried this query but it is incorrect.
SELECT*FROM(SELECTField1,Field2FROMTable1WHEREField4='val1')A
INNERJOIN
SELECT*FROM(SELECTField1,Field3FROMTable1WHEREField4='val2')b
ONA.Field1=B.Fileld1
How to join resulting tables inside a stored procedure?
sql

sql-server-2008

edited Aug 10 at 5:21


marc_s
200k 18 195 361

asked Aug 10 at 5:05


Nalaka526
1,306 7 20
93% accept rate

"joins" work the same way inside of a stored procedure as they do with with pure T-SQL. Your join is simply
wrong. Q: What exactly is it you want to do??? paulsm4 Aug 10 at 5:13

feedback

3 Answers
try this:
you don't have to use SELECT * FROM twice..
SELECT*FROM
(SELECTField1,Field2FROMTable1WHEREField4='val1')A
INNERJOIN
(SELECTField1,Field3FROMTable1WHEREField4='val2')b
ONA.Field1=B.Fileld1
answered Aug 10 at 5:25
Joe G Joseph
3,776 1 10
feedback

Maybe this would help


Withcte_sampleAS(SELECTField1,Field2FROMTable1
WHEREField4='val1')
SELECTField1,Field3FROMTable1ASa
INNERJOINcte_sampleONa.Field1=cte_sample.Field1AND
WHEREa.Field4='val2'

31/08/2012 07:41 a.m.

sql server 2008 - Join SQL query results inside stored procedure - Stack ...

2 de 2

http://stackoverflow.com/questions/11895767/join-sql-query-results-insid...

answered Aug 10 at 6:04


Prince Jea
1,160 12
feedback

You are doing some this like this (Just for an example):
SELECT*FROMTable1A
INNERJOIN
SELECT*FROMTable2B
ONA.FIELD1=B.FIELD2
Which is wrong. Because you don't need to write SELECT*FROM twice. Correct one is:
SELECT*FROMTable1A
INNERJOIN
Table2B
ONA.FIELD1=B.FIELD2
So your query should be(Including Create procedure):
CREATEPROCEDUREtestJoining
AS
SELECT*FROM
(SELECTFIELD1,Field2FROMTable1WHEREField4='VAL1')A
INNERJOIN
(SELECTFIELD1,Field3FROMTable1WHEREField4='VAL2')B
ONA.FIELD1=B.FIELD1
GO
See this fiddle.
Other way to select data from the same table is:
SELECTA.Field1,A.Field2,B.Field3FROMTable1A
INNERJOIN
Table1B
ONA.FIELD1=B.FIELD1
WHEREA.Field4='VAL1'
ANDB.Field4='VAL2'
See this fiddle
edited Aug 10 at 10:03

answered Aug 10 at 9:54


hims056
2,932 1 6 19

+1 for the SQLFiddle reference. Cool - thank you! paulsm4 Aug 10 at 15:54

feedback

Not the answer you're looking for? Browse other questions tagged sql sql-server-2008
or ask your own question.

question feed

31/08/2012 07:41 a.m.

You might also like