为每列添加前缀

时间:2019-01-08 09:01:53

标签: sql sql-server

我的表有很多列,我想为每列添加前缀ABC_

我尝试了以下查询:

    SELECT syscolumns.name as old_column_name, 'ABC_' + syscolumns.name as new_column_name
    FROM sysobjects 
    JOIN syscolumns ON sysobjects.id = syscolumns.id
    WHERE sysobjects.name = 'ABCtable'
    ORDER BY sysobjects.name,syscolumns.colid

当我执行上述查询时,我得到的所有列都带有前缀ABC_,但是在我的表中什么都没有改变。

3 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情。

    DECLARE @Colums AS TABLE(IndexNo INT IDENTITY(1,1), OldCol VARCHAR(MAX), NewCol VARCHAR(MAX))
    INSERT INTO @Colums
    SELECT syscolumns.name as old_column_name, 'ABC_' + syscolumns.name as new_column_name
    FROM sysobjects 
    JOIN syscolumns ON sysobjects.id = syscolumns.id
    WHERE sysobjects.name = 'ABCtable'
    ORDER BY sysobjects.name,syscolumns.colid


    DECLARE @I INT=1;
    WHILE EXISTS(SELECT * FROM @Colums WHERE IndexNo=@I)
    BEGIN
        DECLARE @OldCol VARCHAR(MAX)='', @NewCol VARCHAR(MAX)=''
        SELECT @OldCol='ABCtable.'+OldCol, @NewCol=NewCol FROM @Colums WHERE IndexNo = @I

        EXEC sp_rename @OldCol, @NewCol, 'COLUMN'

        SET @I = @I+1;
    END

答案 1 :(得分:0)

您可以使用sp_rename重命名列/表。

EXEC sp_rename 'TableName.OldColumnName', 'NewColumnName', 'COLUMN'

答案 2 :(得分:0)

您可以如下所示创建光标。请找到以下查询。

create table studInfo (Id int, EmpCode Varchar(20), Name Varchar(20))
insert into studInfo values (1,'1001', 'A'),(2, '1002','B'), (3, '1003','C'), (4,'1004', 'D'), (5,'1005', 'E')

select * from studInfo

Declare @OldSQLcolName Varchar(50)
Declare @NewColName Varchar(50)

DECLARE RenameCursor CURSOR FOR
SELECT 'studInfo.' + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'studInfo'

OPEN RenameCursor;
FETCH NEXT FROM RenameCursor INTO @OldSQLcolName;

WHILE @@FETCH_STATUS = 0
   BEGIN      
      set @NewColName = 'ABC_' + Replace(@OldSQLcolName,'studInfo.','')
      --select @OldSQLcolName, @NewColName

      EXEC sp_rename @OldSQLcolName, @NewColName, 'COLUMN'
      FETCH NEXT FROM RenameCursor INTO @OldSQLcolName;   
   END

CLOSE RenameCursor
DEALLOCATE RenameCursor

select * from studInfo
drop table studInfo

更新列名前后的输出如下所示

enter image description here

您可以找到实时演示Live Demo Here