How to get data related from #parts table based on company id and in case of table #company not have companyid then display all data ?

ahmed salah 3,216 Reputation points
2022-09-28T10:10:51.333+00:00

I work on sql server 2019 i face issue
i need to write join display data from table #parts
based on values exist for #company in case of #company have companyid then get data related
if #company table not have any companyid then get all data from table #parts

create table #company  
(  
companyid int  
)  
insert into #company(companyid)  
values  
(1234)  
  
create table #parts  
(  
PartId int,  
CompanyId int  
)  
insert into #parts(PartId,CompanyId)  
values  
(1255512,1234),  
(1255901,1234),  
(1255541,1234),  
  
(3050512,5591),  
(3050913,5591),  
(1255971,5591)  

what i try   

select p.partid,p.companyid from #parts p  
inner join #company c on c.companyid=p.companyid  

so if #company not have any company
then display all data on table #parts
if table #company have companyid then get companyid data related from table #parts

I need to do it on one statment please
so How to do it on one statment

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,785 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,637 questions
0 comments No comments
{count} votes

Accepted answer
  1. Wilko van de Velde 2,226 Reputation points
    2022-09-28T12:03:01.67+00:00

    Do you mean?

     select p.partid,p.companyid from #parts p  
     left join #company c on c.companyid=p.companyid  
    

2 additional answers

Sort by: Most helpful
  1. NikoXu-msft 1,916 Reputation points
    2022-09-29T02:46:51.507+00:00

    Hi @ahmed salah ,

    (INNER) JOIN: Returns records that have matching values in both tables
    LEFT (OUTER) JOIN: Returns all records from the left table, and the matched records from the right table.
    245833-image.png

    For your case, it is still recommended to use a left join, so that you can see the effect more intuitively.

    Best regards
    Niko

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment"

    0 comments No comments

  2. SunCrop Group 0 Reputation points
    2024-01-16T16:41:33.5766667+00:00

    SunCrop Group is a dynamic and multifaceted conglomerate based in Pakistan, with a rich legacy of excellence and innovation. https://www.suncropgroup.com/

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.