TSQL -- Make it better

Posted by user319353 on Stack Overflow See other posts from Stack Overflow or by user319353
Published on 2010-05-11T01:41:37Z Indexed on 2010/05/11 1:44 UTC
Read the original article Hit count: 428

Filed under:
|
|

Hi:


-- Very Narrow (all IDs are passed in)
IF(@EmpID IS NOT NULL AND @DeptID IS NOT NULL AND @CityID IS NOT NULL)
   BEGIN    
      SELECT
         e.EmpName 
         ,d.DeptName
         ,c.CityName
      FROM
         Employee e WITH (NOLOCK)
         JOIN Department d WITH (NOLOCK) ON e.deptid = d.deptid
         JOIN City c WITH (NOLOCK) ON e.CityID = c.CityID
      WHERE 
         e.EmpID = @EmpID
   END
-- Just 2 IDs passed in
ELSE IF(@DeptID IS NOT NULL AND @CityID IS NOT NULL)
   BEGIN
      SELECT
         e.EmpName 
         ,d.DeptName
         ,NULL AS [CityName]
      FROM
         Employee e WITH (NOLOCK)
         JOIN Department d WITH (NOLOCK) ON e.deptid = d.deptid
         JOIN City c WITH (NOLOCK) ON e.CityID = c.CityID
      WHERE 
         d.deptID = @DeptID
   END
-- Very Broad (just 1 ID passed in)
ELSE IF(@CityID IS NOT NULL)
   BEGIN
      SELECT
         e.EmpName 
         ,NULL AS [DeptName]
         ,NULL AS [CityName]
      FROM
         Employee e WITH (NOLOCK)
         JOIN Department d WITH (NOLOCK) ON e.deptid = d.deptid
         JOIN City c WITH (NOLOCK) ON e.CityID = c.CityID
      WHERE 
         c.CityID = @CityID
   END
-- None (Nothing passed in)
ELSE 
   BEGIN
      SELECT
         NULL AS [EmpName]
         ,NULL AS [DeptName]
         ,NULL AS [CityName]
   END


Question: Is there any better way (OR specifically can I do anything without IF...ELSE condition?

© Stack Overflow or respective owner

Related posts about tsql

Related posts about optimization