问题
What is the best practice when it comes to renaming a table column using SQL (MS SQL Server 2005 variant)? This assumes that there is data in the column that must be preserved.
回答1:
You have to use a stored proc to rename a column. The following will rename your column from 'oldColumnName' to 'newColumnName' without affecting any data.
EXEC sp_rename 'tableName.[oldColumnName]', 'newColumnName', 'COLUMN'
Obviously you'll have to update any code / stored procs / SQL that uses the old name manually.
回答2:
I had the same problem today, and the solution was kill all processes on the database, cause the processes was locked the transactions. I was executed the procedure sp_rename, but the problem was not resolved. So i was kill the processes in the database and the proc works.
USE MASTER
GO
--Kill all the connections opened in database.
DECLARE @dbname sysname
SET @dbname = 'database_name'
DECLARE @spid int
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname)
WHILE @spid IS NOT NULL
BEGIN
EXECUTE ('KILL ' + @spid)
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname) AND spid > @spid
END
SELECT request_session_id
FROM sys.dm_tran_locks
WHERE resource_database_id = DB_ID('database_name')
来源:https://stackoverflow.com/questions/1255903/renaming-a-column-in-ms-sql-server-2005