INFORMATION_SCHEMA.COLUMNS从结果中删除列名称

时间:2016-06-03 04:13:12

标签: sql sql-server tsql sql-server-2012

我有以下查询:

USE db183
SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'SCHEDULE_%' 
   OR COLUMN_NAME LIKE 'EMPINFO_%' 
   OR COLUMN_NAME LIKE 'AVAIL_%' 
   OR COLUMN_NAME LIKE 'TRAINING_%' 
ORDER BY 
    CASE
        WHEN COLUMN_NAME LIKE 'SCHEDULE_%' THEN 0  
        WHEN COLUMN_NAME LIKE 'EMPINFO_%' THEN 1 
        WHEN COLUMN_NAME LIKE 'AVAIL_%' THEN 2 
        WHEN COLUMN_NAME LIKE 'TRAINING_%' THEN 3
    END, ORDINAL_POSITION ASC

我想不包括列名 EMPINFO_empName

但是,尝试这个时:

USE db183
SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'SCHEDULE_%' 
   OR COLUMN_NAME LIKE 'EMPINFO_%' 
   OR COLUMN_NAME LIKE 'AVAIL_%' 
   OR COLUMN_NAME LIKE 'TRAINING_%' 
   AND NOT COLUMN_NAME LIKE '%_empName' /*<-- NEW ADDED CODE HERE */
ORDER BY 
    CASE
        WHEN COLUMN_NAME LIKE 'SCHEDULE_%' THEN 0  
        WHEN COLUMN_NAME LIKE 'EMPINFO_%' THEN 1 
        WHEN COLUMN_NAME LIKE 'AVAIL_%' THEN 2 
        WHEN COLUMN_NAME LIKE 'TRAINING_%' THEN 3
    END, ORDINAL_POSITION ASC

似乎没有取出那个特定的列名 - 它仍然在输出中列出,就像第一个查询一样。

我猜我的语法不正确,但我没有收到任何错误。

2 个答案:

答案 0 :(得分:2)

它不仅仅是information_schema

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (COLUMN_NAME LIKE 'SCHEDULE_%' 
   OR COLUMN_NAME LIKE 'EMPINFO_%' 
   OR COLUMN_NAME LIKE 'AVAIL_%' 
   OR COLUMN_NAME LIKE 'TRAINING_%' ) --this is what you need
   AND NOT COLUMN_NAME LIKE '%_empName' /*<-- NEW ADDED CODE HERE */

答案 1 :(得分:0)

您需要在LIKE声明中转义下划线:

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE 'SCHEDULE[_]%' OR
      COLUMN_NAME LIKE 'AVAIL[_]%' OR
      COLUMN_NAME LIKE 'TRAINING[_]%' OR
      (COLUMN_NAME LIKE 'EMPINFO[_]%' AND COLUMN_NAME NOT LIKE '%[_]empName%')

实际上,如果您真的只想排除一个列,那么只需使用全名:

WHERE COLUMN_NAME <> 'EMPINFO_empName'