MS SQL存储过程获取值

时间:2014-06-19 02:04:19

标签: sql sql-server

我有3张桌子

Staff table:

EmpId   CandidateId
------------------------
  1          2


Candidate table:

CandidateId    Firstname    Last name    CountryId   PassportCountry
--------------------------------------------------------------------
     1           Mark        Antony          2            3           
     2           Joy         terry           1            3

Country:

CountryId      Name
---------------------------
    1           USA
    2           UK
    3           Australia

用户将在我需要的查询字符串中传递EmpId,以根据empId显示候选人详细信息。我只有一个country表,并将该表用于country,护照端口国家/地区。所以当我得到候选值时,我需要获得country name

如何编写存储过程以获取候选详细信息。我不擅长sql。你们能帮助我吗?提前谢谢。

您好我尝试了下面的脚本来获取国家/地区名称和护照国家/地区名称。我可以获得国家名称,但不能获得护照国家。

SELECT 
FirstName,
LastName,
PassportCountry,
Country.CountryName as Country
from Candidate 
inner join Country
on country.CountryId=candidate.country
where CandidateId=@CandidateId;

1 个答案:

答案 0 :(得分:0)

这应该让你朝着正确的方向前进。

基本上,由于你引用了两次Country表,你需要加入它两次。

declare @staff table (EmpId int, CandidateId int)
insert into @staff values (1, 2 )

declare @Candidate table (CandidateId int, Firstname nvarchar(50), Lastname nvarchar(50), CountryId int, PassportCountry int)
insert into @Candidate
values (1, 'Mark', 'Antony', 2, 3),
       (2, 'Joy', 'Terry', 1, 3)

declare @Country table (CountryId int, Name nvarchar(50))
insert into @Country 
values (1, 'USA'),
       (2, 'UK'),
       (3, 'Australia')


declare @empID int
set @empID = 1

SELECT 
FirstName,
LastName,
t2.Name as PersonCountry,
t3.Name as PassportCountry
from @staff s
inner join @Candidate t1 on s.CandidateId = t1.CandidateId
inner join @Country t2 on t1.CountryId=t2.CountryId
inner join @Country t3 on t1.PassportCountry=t3.CountryId
where s.EmpId=@empID;