Renaming a column in MS SQL Server 2005

旧城冷巷雨未停 提交于 2019-11-27 15:41:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!