SQL Server +条件连接

时间:2012-04-19 07:38:56

标签: sql-server

有没有办法可以执行这样的条件连接:

   CREATE TABLE #Entity 
   (    
    [AutoID] [int],
    [Code] [nvarchar](50) NOT NULL,
   )

    INSERT #Entity
    EXEC Entity_GetEntitiesByUserId @UserID

    DECLARE @Condition bit = 0

    SELECT * FROM [Stuff] s

       IF @Condition = 1 BEGIN

       INNER JOIN 
       (
        SELECT Code as eCode from
        #Entity
       ) e
        ON E.eCode  = s.EntityCode 

       END

       WHERE DeletedBy IS NULL

感谢。

1 个答案:

答案 0 :(得分:7)

这将符合您的要求:

SELECT * 
FROM [Stuff] s
WHERE 
 DeletedBy IS NULL 
 and (@Condition = 0 or s.EntityCode in (select E.code from #Entitye))