Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Join function between two queries.

Author  Topic 

wleonard
Starting Member

30 Posts

Posted - 2011-02-28 : 15:42:08
I am trying to combine two queries using SQL Join in Transact-SQL. The first query is written:

begin
insert into ##emailblast select lab_key, lab_name, lab_e_mail
from tbllabel where lab_key in
(select distinct lab_key from tblprospectuserhierarchychoice
where substring(uhc_code, 1, 7) in (
select distinct uhc_code from
(select * from tblUserhierarchychoice
where isnumeric(uhc_parent_code) = 1) tblUserhierarchychoice
where uhl_level = 'M' and (uhc_description like '%gto%' or uhc_description like '%tempest%' or uhc_description like '%lemans%')
and isnumeric(uhc_parent_code) = 1
and uhc_parent_code >= @begyear and uhc_parent_code <= @endyear)) and lab_e_mail is not null and len(lab_e_mail) > 0






I want to join this query with:

(SELECT model, bodystyle FROM (SELECT DISTINCT b.uhc_description model, c.uhc_description bodystyle
FROM tblUserhierarchychoice a, tblUserhierarchychoice b, tblUserhierarchychoice c
where c.uhl_level = 'B' and a.uhl_level = 'A' and
b.uhl_level = 'M' and a.udh_parent_level = b.uhl_level and a.uhc_parent_code = b.uhc_code
and c.udh_parent_level = a.uhl_level and c.uhc_parent_code = a.uhc_code) a WHERE bodystyle like '%'+ rtrim(@body) + '%')

Please help. Thanks.

Will Leonard

MIK_2008
Master Smack Fu Yak Hacker

1054 Posts

Posted - 2011-03-01 : 10:02:32
Not sure what you are trying to ask. but hope the following would help you on the right track ...

If you need to perform some kind of join operation on two dataset, coming out of two different queries..then you can do

Select A.*,B.*
From (Your First Select Statement) A --Query inside brackets and aliasing it with a name e.g. A is working as Table
Inner/Left/Right Join (Your First Select Statement) B --Query inside brackets and aliasing it with a name e.g. B is working as Table
ON A.ColumnName=B.ColumnName -- the joining Conditions


However if you are looking for just to append the result of one query with another then You can do it via placing UNION or UNION ALL between both queries e.g.

Your 1st query
UNION or Union ALL
Your 2nd query

Note that the number of columns should be equal, with same datatype and with Same Sequence in both queries for the case of UNION and UNION ALL


Cheers
MIK
Go to Top of Page
   

- Advertisement -