查询CASE以及是否存在列而不是无效列错误

时间:2016-09-01 17:58:42

标签: sql-server sql-server-2012 case

这是我当前的SQL Server查询:

SELECT 
     COUNT(*) over () as countNum,
     [F1] AS STANDARDandOBJ,
     [F2] AS CLUSTER,
     [F3] AS OBJECTIVE,
     [F4] AS EXTRA0,
     CASE 
        WHEN COL_LENGTH('[tmpExcelDB].[dbo].[''Nursing$'']', [F5]) IS NULL 
        THEN 'NO' ELSE CONCAT([F1], [F2]) 
     END AS COMBINEF1F2 
FROM 
    [tmpExcelDB].[dbo].['Nursing$'] 
WHERE 
    LOWER(F3) NOT LIKE 'planning tools-%'

只要表格中包含F5,这就可以正常工作。否则,它会抛出一个错误:

  

无效的列名称'F5'。

如果有F5列或者不存在F5列,我该如何修改上述查询?

2 个答案:

答案 0 :(得分:0)

您可以检查sys.objects和sys.columns以查看它是否存在并在CASE逻辑中使用它。

--this will be 0 if the column isn't there, and 1 if it is there.
declare @isThere int
set @isThere = (select
                count(c.name)
                from tmpExcelDB.sys.objects o
                inner join tmpExcelDB.sys.columns c on o.object_id = c.object_id
                where o.name like 'Nursing$%' and c.name = 'F5')

SELECT 
     COUNT(*) over () as countNum,
     [F1] AS STANDARDandOBJ,
     [F2] AS CLUSTER,
     [F3] AS OBJECTIVE,
     [F4] AS EXTRA0,
     CASE 
        WHEN @isThere = 0 THEN 'NO'     --if the column doesn't exist return 'NO' 
        ELSE CONCAT([F1], [F2])         --other wise, do the CONCAT()
     END AS COMBINEF1F2 
FROM 
    [tmpExcelDB].[dbo].['Nursing$'] 
WHERE 
    LOWER(F3) NOT LIKE 'planning tools-%'

或者,您可以使用以下

修复语法问题
SELECT 
         COUNT(*) over () as countNum,
         [F1] AS STANDARDandOBJ,
         [F2] AS CLUSTER,
         [F3] AS OBJECTIVE,
         [F4] AS EXTRA0,
         CASE 
            WHEN COL_LENGTH('tmpExcelDB.dbo.Nursing$', 'F5') IS NULL THEN  'NO'     --if the column doesn't exist return 'NO' 
            ELSE CONCAT([F1], [F2])                                                 --other wise, do the CONCAT()
         END AS COMBINEF1F2 
    FROM 
        [tmpExcelDB].[dbo].['Nursing$'] 
    WHERE 
        LOWER(F3) NOT LIKE 'planning tools-%'

答案 1 :(得分:0)

根据COL_LENGTH元数据函数的文档,column param是nvarchar类型的表达式。所以你应该传入一个字符串,即'F5'而不是[F5]。我相信方括号向编译器指示您要在FROM语句的SELECT部分中使用该列,因此,在指定不存在的列时,您的“无效列名称”错误。

我也相信table param也不需要方括号。我会按如下方式重写查询,根据文档,它应该在出错时返回NULL

SELECT 
     COUNT(*) over () as countNum,
     [F1] AS STANDARDandOBJ,
     [F2] AS CLUSTER,
     [F3] AS OBJECTIVE,
     [F4] AS EXTRA0,
     CASE 
        WHEN COL_LENGTH('tmpExcelDB.dbo.Nursing$', 'F5') IS NULL 
        THEN 'NO' ELSE CONCAT([F1], [F2]) 
     END AS COMBINEF1F2 
FROM 
    [tmpExcelDB].[dbo].['Nursing$'] 
WHERE 
    LOWER(F3) NOT LIKE 'planning tools-%'