troubleshooting Question

MS SQL Server select from Sub Table

Avatar of Larry Brister
Larry BristerFlag for United States of America asked on
Microsoft SQL ServerMicrosoft SQL Server 2008
14 Comments1 Solution316 ViewsLast Modified:
My code below works as long as @ID exists in @table2
But If I set @ID = 4
Then...nothing comes back when it need it to return test@server2.com

DECLARE @table1 TABLE
    (
      MailServerID INT NULL ,
      MailServer VARCHAR(100) ,
      EmailAddress VARCHAR(100)
    );

INSERT  INTO @table1
        ( MailServerID, MailServer, EmailAddress )
VALUES  ( 1, -- ID - int
          'server1',  -- MailServerID - int
          'test@server1.com' ),
        ( 2, -- ID - int
          'server2',  -- MailServerID - int
          'test@server2.com' );

DECLARE @table2 TABLE
    (
      ID INT IDENTITY(1, 1) ,
      MailServerID INT ,
      EmailAddress VARCHAR(100)
    );

INSERT  INTO @table2
        ( MailServerID, EmailAddress )
VALUES  ( 2,  -- MailServerID - int
          'test@serversubtable_100.com' ),
        ( 2,  -- MailServerID - int
          'test@serversubtable_200.com.com' );

DECLARE @MailServerID INT;
SET @MailServerID = 2;

DECLARE @ID INT;
SET @ID = 1;
--If I set @ID = 4 nothing comes back when it should return test@server2.com

SELECT  ISNULL(t2.EmailAddress, t1.EmailAddress) EmailAddress
FROM    @table1 t1
        LEFT JOIN @table2 t2 ON t1.MailServerID = t2.MailServerID
WHERE   t1.MailServerID = @MailServerID
        AND @ID = t2.ID;
ASKER CERTIFIED SOLUTION
Vitor Montalvão
IT Engineer
Join our community to see this answer!
Unlock 1 Answer and 14 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 14 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros