SQL Server重命名列名

时间:2015-11-11 16:19:14

标签: sql sql-server sql-server-2008-r2 sql-server-2012

我有以下查询来收集表的列名:

SELECT COLUMN_NAME 
FROM theDBNameHere.INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'markers'

这样可以很好地为我提供该表所需的列名。但是,我想将列名重命名为其他名称。我尝试了以下方法:

SELECT  venueID AS 'Venue ID', 
        venueEventDate AS 'Venue Date', 
        venueCounty AS 'Venue County', 
        venueAdvocate AS 'Venue Advocate', 
        venueSpanish AS 'in Spanish', 
        lastUpdated AS 'Last Updated', 
        updatedBy AS 'Updated By', 
        SysSrcLoadDt AS SysSrcLoadDt 
FROM theDBNameHere.INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'markers'

它抛给我的错误几乎是在说

  

无效的列名' venueXXXXXXXX'

如何使用上面的查询更改默认列名?这首先是否可以做到?

3 个答案:

答案 0 :(得分:2)

如果您只想要列名:

SELECT  venueID        AS [Venue ID], 
        venueEventDate AS [Venue Date], 
        venueCounty    AS [Venue County], 
        venueAdvocate  AS [Venue Advocate], 
        venueSpanish   AS [in Spanish], 
        lastUpdated    AS [Last Updated], 
        updatedBy      AS [Updated By], 
        SysSrcLoadDt   AS [SysSrcLoadDt] 
FROM markers
WHERE 1 = 2  -- column headers only, comment if you want rows also

或评论中提出的Sean Lange

SELECT  '' AS [Venue ID], 
        '' AS [Venue Date], 
        '' AS [Venue County], 
        '' AS [Venue Advocate], 
        '' AS [in Spanish], 
        '' AS [Last Updated], 
        '' AS [Updated By], 
        '' AS [SysSrcLoadDt] 
WHERE 1 = 2;

LiveDemo

修改

如果您想在一列中输入姓名:

SELECT *
FROM (VALUES ('Venue ID'), ('Venue Date'), ('Venue County'),
     ('Venue Advocate'), ('in Spanish'),  ('Last Updated'),
     ('Updated By'), ('SysSrcLoadDt') ) AS t(column_name);

LiveDemo2

输出:

╔════════════════╗
║  column_name   ║
╠════════════════╣
║ Venue ID       ║
║ Venue Date     ║
║ Venue County   ║
║ Venue Advocate ║
║ in Spanish     ║
║ Last Updated   ║
║ Updated By     ║
║ SysSrcLoadDt   ║
╚════════════════╝

答案 1 :(得分:2)

您可能需要CASE声明

SELECT  CASE WHEN COLUMN_NAME = 'venueID'
             THEN 'Venue ID'
             WHEN COLUMN_NAME = 'venueEventDate'
             THEN 'Venue Date'
             WHEN COLUMN_NAME = 'venueCounty'
             THEN 'Venue County'
             -- do the rest of columns here
            END AS COLUMN_NAME
FROM theDBNameHere.INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'markers'

答案 2 :(得分:0)

如果需要重命名列名,请使用Alter表和Rename Column关键字...

ALTER TABLE table_name
RENAME COLUMN old_name to new_name;