문제

I am trying to rename a column name in w3schools website

ALTER TABLE customers
  RENAME COLUMN contactname to new_name;

However, the above code throws syntax error. What am I doing wrong?

도움이 되었습니까?

해결책

You can try this to rename the column in SQL Server:-

sp_RENAME 'TableName.[OldColumnName]' , '[NewColumnName]', 'COLUMN'

sp_rename automatically renames the associated index whenever a PRIMARY KEY or UNIQUE constraint is renamed. If a renamed index is tied to a PRIMARY KEY constraint, the PRIMARY KEY constraint is also automatically renamed by sp_rename. sp_rename can be used to rename primary and secondary XML indexes.

For MYSQL try this:-

ALTER TABLE table_name CHANGE [COLUMN] old_col_name new_col_name

다른 팁

From "Learning PHP, MySQL & JavaScript" by Robin Nixon pg 185. I tried it and it worked.

ALTER TABLE tableName CHANGE oldColumnName newColumnName TYPE(#);

note that TYPE(#) is, for example, VARCHAR(20) or some other data type and must be included even if the data type is not being changed.

@Hannah's answer definitely helped me there but, as it took me some time to translate the syntax into real-life, I thought it might help someone to get an actual real-life example on how to use this syntax on MySQL.

1.So here again is the syntax:

ALTER TABLE tableName CHANGE oldColumnName newColumnName TYPE(#);

NB: TYPE(#) is, for example, VARCHAR(255) or some other data type and must be included even if the data type is not being changed.

2.Here is my real-life example, where "dashboard_dummy" is my table name, "product_code" my old column name and "order_id" my new column name:

ALTER TABLE dashboard_dummy CHANGE COLUMN product_code order_id int;

Hope it helps!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top