How to replace space with '_' in all column names in SQL Server?

xqnpmsa8  于 2023-10-15  发布在  SQL Server
关注(0)|答案(1)|浏览(150)

I have a table with bunch of columns such as Policy Number, Person name and etc... How do I write a code that replaces the space between "Policy Number" to "Policy_Number"? In short, I want to modify all the column names to replace space in between the characters to underscore. Thank you for helping!

bmvo0sr5

bmvo0sr51#

In SQL Server, you can dynamically rename column names to replace spaces with underscores using a combination of SQL queries and T-SQL script. Below is a code snippet that demonstrates how to achieve this:

DECLARE @TableName AS VARCHAR(128)
DECLARE @OldColumnName AS VARCHAR(128)
DECLARE @NewColumnName AS VARCHAR(128)
DECLARE @SQL AS VARCHAR(1000)

-- Set the name of the table you want to modify
SET @TableName = 'YourTableName'

-- Declare a cursor to select column names from the table
DECLARE ColumnCursor CURSOR FOR
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @TableName

-- Open the cursor and loop through all the columns to rename them
OPEN ColumnCursor

FETCH NEXT FROM ColumnCursor INTO @OldColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @NewColumnName = REPLACE(@OldColumnName, ' ', '_')
    
    -- If the column name actually has a space, proceed to rename it
    IF @NewColumnName <> @OldColumnName
    BEGIN
        SET @SQL = 'EXEC sp_rename ''' + @TableName + '.' + @OldColumnName + ''', ''' + @NewColumnName + ''', ''COLUMN'''
        EXEC(@SQL)
    END

    FETCH NEXT FROM ColumnCursor INTO @OldColumnName
END

-- Close and deallocate the cursor
CLOSE ColumnCursor
DEALLOCATE ColumnCursor

相关问题