Renaming a column in MS SQL Server 2005

2019-01-23 11:55发布

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.

2条回答
唯我独甜
2楼-- · 2019-01-23 12:30

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.

查看更多
SAY GOODBYE
3楼-- · 2019-01-23 12:45

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') 
查看更多
登录 后发表回答