How do you change the datatype of a column in SQL Server?
Solution 1
ALTER TABLE TableName
ALTER COLUMN ColumnName NVARCHAR(200) [NULL | NOT NULL]
EDIT As noted NULL/NOT NULL should have been specified, see Rob's answer as well.
Solution 2
Don't forget nullability.
ALTER TABLE <schemaName>.<tableName>
ALTER COLUMN <columnName> nvarchar(200) [NULL|NOT NULL]
Solution 3
Use the Alter table statement.
Alter table TableName Alter Column ColumnName nvarchar(100)
Solution 4
The syntax to modify a column in an existing table in SQL Server (Transact-SQL) is:
ALTER TABLE table_name
ALTER COLUMN column_name column_type;
For example:
ALTER TABLE employees
ALTER COLUMN last_name VARCHAR(75) NOT NULL;
This SQL Server ALTER TABLE
example will modify the column called last_name
to be a data type of VARCHAR(75)
and force the column to not allow null values.
see here
Solution 5
For changing data type
alter table table_name
alter column column_name datatype [NULL|NOT NULL]
For changing Primary key
ALTER TABLE table_name
ADD CONSTRAINT PK_MyTable PRIMARY KEY (column_name)
![Ascalonian](https://i.stack.imgur.com/PMj3B.jpg?s=256&g=1)
Ascalonian
Operating Systems: Linux (RHEL, Ubuntu) Windows 95 - 10 Mac OSX Tools: Apache Server, Tomcat, JBoss, ESB, GIT, SVN, SQL Developer, Maven, Ant, Gradle Jenkins, Confluence, JIRA, BitBucket, Docker, Gherkin & Cucumber, ActiveMQ, ZeroMQ Web Languages: HTML(5), JSP & JSTL, CSS(3), XML, JavaScript, AJAX, JQuery Programming Languages: Java/J2EE, PL/SQL, SQL APIs and Libraries: JPA, Apache POI, JSoup, Google Gson, Liquibase, ElasticSearch, Logstash, Log4j, Apache Commons Apache Shiro, Apache Tika, Apache HTTPClient, RESTEasy, Swagger, Apache Camel Frameworks: J2EE, Spring MVC, Hibernate, Spring, Spring JPA, Spring Data, Spring Boot, JOOQ, Swing Databases: Oracle, PostgreSQL, MS SQL Server Other: Agile, Scrum, Kanban, MS Project, MS Office Suite
Updated on November 11, 2021Comments
-
Ascalonian over 2 years
I am trying to change a column from a
varchar(50)
to anvarchar(200)
. What is the SQL command to alter this table?