如何通过 T-SQL 更改 SQL Server 表中列的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15251177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 14:05:24  来源:igfitidea点击:

How to change the length of a column in a SQL Server table via T-SQL

sqlsql-serversql-server-2008tsql

提问by Anton Hughes

I am looking to find out how to alter a fields properties contained in an SQL Server 2008 table via an SQL script.

我正在寻找如何通过 SQL 脚本更改 SQL Server 2008 表中包含的字段属性。

I'm looking to change the 'Length' property specifically.

我正在寻找专门更改“长度”属性。

Does anybody know how to do this?

有人知道怎么做这个吗?

Thanks

谢谢

回答by Lamak

So, let's say you have this table:

所以,假设你有这张表:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1to VARCHAR(20). What you need to do is this:

并且您想更改Col1VARCHAR(20). 你需要做的是:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLEwill fail.

由于列的长度变大了,这将毫无问题地工作。如果您想将其更改为VARCHAR(5),那么您首先需要确保列中没有包含更多字符的值,否则ALTER TABLE将失败。