如果要连接的列为空,连接是否仍然有效?

时间:2010-07-14 02:05:04

标签: sql stored-procedures null

我有这个存储过程,当我添加连接时,我得不到任何结果。这是因为用于连接条件的列ForClientID是否为空?这会影响表格的结果吗?如果我选择具有Appointment.ForClientID而不是Client.Name的表,则表的其余部分将加载ForClientID列为null。在此先感谢,这是一个非常有用的社区。

Create procedure GetAppointmentsByProfessionalName(@ProfessionalName varchar(256))
as
    declare @ProfessionalID uniqueidentifier
    set @ProfessionalID = (select UserId from aspnet_Users where UserName = @ProfessionalName)

    select  Appointment.AppointmentID as 'Appointment ID', 
            Client.Name as 'Client Name',
            CONVERT(VARCHAR(10),Appointment.ProposedDate,111) as 'Date', 
            CONVERT(CHAR(8), Appointment.ProposedTime, 114)as  'Time', 
            Appointment.ClientDescription as 'Client Notes', 
            Appointment.Confirmed as 'Confirmed Appointment'
    from Appointment join Client on Client.ClientID = Appointment.ForClientID
    where Appointment.ForProfessionalID = @ProfessionalID
go

2 个答案:

答案 0 :(得分:3)

围绕NULL的行为是不同类型JOIN之间的主要区别。阅读http://en.wikipedia.org/wiki/Join_%28SQL%29,虽然维基百科是关于该主题的一篇非常好的文章。

答案 1 :(得分:2)

使用OUTER JOIN进行重写,以考虑Appointment.ForClientIDNULL能否并使用@ProfessionalID替换本地变量INNER JOIN

CREATE PROCEDURE GetAppointmentsByProfessionalName
@ProfessionalName VARCHAR(256)
AS
BEGIN

   SELECT Appointment.AppointmentID AS 'Appointment ID', 
          COALESCE(Client.Name, '{{NO CLIENT}}') AS 'Client NAME',
          CONVERT(VARCHAR(10),Appointment.ProposedDate,111) AS 'Date', 
          CONVERT(CHAR(8), Appointment.ProposedTime, 114)AS  'Time', 
          Appointment.ClientDescription AS 'Client Notes', 
          Appointment.Confirmed AS 'Confirmed Appointment'
     FROM Appointment 
          LEFT OUTER JOIN Client 
             ON Client.ClientID = Appointment.ForClientID
          INNER JOIN aspnet_Users
             ON aspnet_Users.UserId = Appointment.ForProfessionalID
    WHERE aspnet_UsersUserName = @ProfessionalName;

END;