仅当列存在时左外连接(SQL服务器)

时间:2012-11-16 12:27:11

标签: sql-server join where-clause

我正在使用SQL Server Express,我正在尝试使用LEFT OUTER JOIN从不同的表中提取不同的列。它工作得很好,但只有所有列都存在。所以我一直在阅读过去一小时如何添加条件,以便只有列存在才能完成LEFT OUTER JOIN

请参阅下面的代码(问题是最后一个LEFT OUTER JOIN,因为a.[Page Path]不存在):

SELECT 
    b.[Page ID],
    ISNULL(b.[Page Group],'Other Landing Page') AS [Landing Page Group],
    ISNULL(c.[Page Group],'Other Second Page') AS [Second Page Group],
    ISNULL(d.[Page Group],'Other Page') AS [Page Path Group],
    a.*

FROM [mychoice-data-b9BwZvd] a 


LEFT OUTER JOIN [mychoice-pagedims] b 
ON 
   (a.[Landing Page Path] LIKE b.[Page ID])


LEFT OUTER JOIN [mychoice-pagedims] c 
ON 
   (a.[Second Page Path] LIKE c.[Page ID])


LEFT OUTER JOIN [mychoice-pagedims] d 
ON 
   a.[Page Path] LIKE d.[Page ID] 
   WHERE a.[Page Path] IS NOT NULL

我已尝试IF(EXISTS,但无论我做什么,都会收到错误'无效的列名'页面路径''。

3 个答案:

答案 0 :(得分:2)

我不认为您可以在一个查询中执行此操作,我建议您使用的方式是这样的:

if (
    select COUNT(*) 
    from sys.objects so 
    inner join sys.columns col 
    on so.object_id = col.object_id 
    where so.type = 'U' and so.name = 'tablename' and col.name = 'colname'
) > 0

-- column exists -> write select with the join

else

-- column does not exist, don't include the join

答案 1 :(得分:0)

不,这是不可能的。数据库模式不应该在您手中更改,因此应用程序应该知道它并且只查询存在的表和列。

如果可能的话,您应该更改数据库架构,以便运行查询所需的表格略有不同甚至更好,这样您根本不需要在多个表上运行它。可能是将单个表中的信息与指示其来源的列组合在一起。

答案 2 :(得分:0)

使用动态SQL

DECLARE 
    @SQL VARCHAR(MAX)='
SELECT 
    b.[Page ID],
    ISNULL(b.[Page Group],''Other Landing Page'') AS [Landing Page Group],
    ISNULL(c.[Page Group],''Other Second PAGE'') AS [Second Page Group],
    ISNULL(d.[Page Group],''Other Page'') AS [Page Path Group],
    a.*

FROM [mychoice-data-b9BwZvd] a 


LEFT OUTER JOIN [mychoice-pagedims] b 
ON 
   (a.[Landing Page Path] LIKE b.[Page ID])


LEFT OUTER JOIN [mychoice-pagedims] c 
ON 
   (a.[Second Page Path] LIKE c.[Page ID])


LEFT OUTER JOIN [mychoice-pagedims] d 
ON 
   '+
CASE 
    WHEN EXISTS (
        SELECT  *
        FROM sys.columns C  
        JOIN sys.tables T ON T.object_id = C.object_id  
        LEFT JOIN   sys.schemas S ON S.Schema_id=T.Schema_id 
        WHERE 
            C.Name ='Page Path'  AND
            T.Name ='mychoice-pagedims'         
    )
    THEN    'a.[Page Path] LIKE d.[Page ID]'
    ELSE    '(1=0)'
END+'

WHERE a.[Page Path] IS NOT NULL
'
EXEC(@SQL)