加入不同的表存储过程

时间:2013-06-19 19:53:09

标签: sql stored-procedures

我有这样的存储过程

ALTER Procedure [dbo].[spCarCallFetch] @Carid nvarchar(20)
as
begin
  Select 
      k.tid, k.HBarcode, m.make, t.plateno ,v.vtype, l.locname,
      mdl.model, c.Colname 
  from 
      transaction_tbl t, KHanger_tbl k, make_tbl m, vtype_tbl v, Location_tbl l, Model_tbl mdl, Color_tbl C  
  where 
      t.tbarcode = @carid and t.mkid = m.mkid and v.vtid = t.vtid 
      and t.locid = l.locid and mdl.mdlid = t.mdlid and t.colid = c.colid 
      and t.transactID = k.transactID
end

执行此

exec spCarCallFetch'51891044554'

输出:

tid         HBarcode   make plateno   vtype         locname        model       Colname--------------------------------------------
6           564       BMW   44554    Normal       Fashion Avenue  520          Red

这里的tid取自KeyHanger表,但是对应的tid名称保存在终端表中,实际上我想获取相应的tid名称。

我的表格如下:

KHanger_tbl

transactid                              HBarcode                tid
--------------------------------------- ----------------------------------
19                                      34                      7
22                                      002                     5
21                                      1                       7
23                                      200005                   6

Terminals_tbl

tid         UniqueName
----------- --------------------------------------------------
5           Key Room-1
6           Podium -1
7           Key Room - 2

我想获取相应tid的uniqueName。如何为此编写存储过程?如果有人知道,请帮帮我

1 个答案:

答案 0 :(得分:1)

也许这就是你想要的东西?

正如评论中所建议的那样,显式连接是应该使用的,然后查询应如下所示:

ALTER PROCEDURE [dbo].[spCarCallFetch] @Carid NVARCHAR(20)
AS

BEGIN

  SELECT
    k.tid, k.HBarcode, m.make,
    t.plateno, v.vtype, l.locname,
    mdl.model, c.Colname, te.UniqueName

  FROM transaction_tbl t

  INNER JOIN KHanger_tbl   AS k   ON t.transactID = k.transactID
  INNER JOIN make_tbl      AS m   ON t.mkid = m.mkid 
  INNER JOIN vtype_tbl     AS v   ON v.vtid = t.vtid 
  INNER JOIN Location_tbl  AS l   ON t.locid = l.locid 
  INNER JOIN Model_tbl     AS mdl ON mdl.mdlid = t.mdlid 
  INNER JOIN Color_tbl     AS c   ON t.colid = c.colid 
  INNER JOIN Terminals_tbl AS te  ON k.tid = te.tid

  WHERE t.tbarcode = @carid 

END