如何从存储过程中的3个表中获取一个结果

时间:2014-05-09 19:04:45

标签: sql sql-server stored-procedures

我需要3个表中的一个结果。我如何在存储过程中执行此操作?

以下是我的3个表格: 3 SQL tables

这是我想要的结果:

Result from 3 SWL tables

我尝试了很多代码,但没有任何作用,例如:

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

2 个答案:

答案 0 :(得分:1)

'使用Coalesce()将NULL替换为空字符串,以防您更好:

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

答案 1 :(得分:1)

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

致电程序

EXECUTE dbo.usp_GetResultSet