1

我正在使用 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了,但无论我做什么,我都会收到一个错误“无效的列名'页面路径'”。

4

3 回答 3

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
于 2012-11-16T12:47:20.150 回答
0

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

如果有可能,您应该更改您的数据库架构,以便您需要运行查询的表不会略有不同甚至更好,因此您根本不需要在多个表上运行它。可能是通过将单个表中的信息与表明其来源的列结合起来。

于 2012-11-16T12:51:31.987 回答
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)
于 2012-11-16T14:30:26.550 回答