在INNER JOIN子句中使用OR

时间:2018-10-16 17:29:25

标签: sql sql-server tsql

我有一个动态查询,在其中声明了3个不同的变量,例如:

       DECLARE @JobNoteQuery NVARCHAR(MAX) = IIF(@JobNote = '%' , '' , ' INNER JOIN (SELECT ParentGuid FROM JobNotes JN WITH (NOLOCK) 
                            WHERE JN.Note LIKE ''%''+@JobNote+ ''%''
                            GROUP BY ParentGuid) JN ON P.ProjectGuid = JN.ParentGuid');

       DECLARE @ContactQuery NVARCHAR(MAX) = IIF(@Contact = '%' , '' , ' LEFT JOIN(SELECT
                        [ProjectKey]
                        FROM [ProjectCustomerContact] AS [pcc]
                            LEFT JOIN [Contact] AS [c] ON [c].[ContactKey] = [pcc].[ContactKey]
                        WHERE [c].[LastName] LIKE ''%''+@LastName+''%'') AS [pcc] ON [pcc].[ProjectKey] = [p].[ProjectKey]')

       DECLARE @CustomerQuery NVARCHAR(MAX) = IIF(@Customer = '%' , '' , 'LEFT JOIN(SELECT
                        [ProjectKey]
                        FROM [ProjectCustomer] AS [pc]
                            LEFT JOIN [Customer] AS [c] ON [c].[CustomerKey] = [pc].[CustomerKey]
                        WHERE([c].[Name] LIKE ''%''+@CustName+''%''
                            OR [c].[DBA] LIKE ''%''+@CustName+''%'')) AS [PC] ON [pc].[ProjectKey] = [p].[ProjectKey]')

因此,在选择查询中,我将这些变量用于Joins子句中,例如:

  ...INNER JOIN [Region] AS [re] ON [a].[RegionKey] = [re].[RegionKey]
                          '+@JobNoteQuery+'
                          '+@ContactQuery+'
                          '+@CustomerQuery+'
                       WHERE...

我的问题是。如果我的树形参数返回其值,我的意思是@JobNoteQuery@ContactQuery@CustomerQuery,则始终返回内部连接和左连接,但是如果其中一个不具有值,则值可以为null将返回空列表,因此有什么方法可以在OR中使用INNER JOINS子句?喜欢:

 ...INNER JOIN [Region] AS [re] ON [a].[RegionKey] = [re].[RegionKey]
          OR
                              '+@JobNoteQuery+'
          OR
                              '+@ContactQuery+'
          OR
                              '+@CustomerQuery+'
                           WHERE...

那不可能吗?问候

1 个答案:

答案 0 :(得分:1)

将数据插入到临时表中,然后您就可以开始使用提供的具有相同列数据类型的并集来获取三个查询中每个查询的组合结果集。或者,您在临时表中保留了所需的联接条件的数据,否则内部联接在那时候将是一件小事。