MHP
MHP

Reputation: 81

How to get one result from 3 tables in stored procedure

I need one result from 3 tables. How do I do that in a stored procedure?

Here are my 3 tables: 3 SQL tables

Here is the result I want:

Result from 3 SWL tables

I have try many code but nothing works, example:

SELECT a.id, a.name, b.name, c.name 
FROM TableA AS a, TableB as b, TableC as c
WHERE a.idTableB = b.id 

Upvotes: 0

Views: 30

Answers (2)

AjV Jsy
AjV Jsy

Reputation: 6075

I've used Coalesce() to replace NULLs with empty strings in case that's better for you :

SELECT
  a.id,
  a.name AS nameTableA,
  Coalesce(b.name,'') AS nameTableB,
  Coalesce(c.name,'') AS nameTableC
FROM TableA AS a
  LEFT JOIN TableB AS b ON a.idTableB = b.id 
  LEFT JOIN TableC AS c ON b.idTableC = c.id

Upvotes: 1

M.Ali
M.Ali

Reputation: 69514

CREATE PROCEDURE dbo.usp_GetResultSet
AS
BEGIN
   SET NOCOUNT ON;

  SELECT A.ID 
        ,A.Name   AS nameTableA
        ,B.Name   AS nameTableB
        ,C.Name   AS nameTableC
  FROM TABLEA A LEFT JOIN TABLEB B
  ON A.idTableB = B.ID
  LEFT JOIN TABLEC C
  ON C.idTableC = C.ID

END

Call Procedure

EXECUTE dbo.usp_GetResultSet

Upvotes: 1

Related Questions