SQL:将 COLUMN 更改为较短的 CHAR(n) 类型
我正在使用 MS SQL SERVER 2003。我想更改一个表中的列以减少条目中的字符。这与这个问题相同:更改表列以接受更多字符< /a> 除了我想要更少的字符而不是更多的事实。
我的一个表中有一个列包含九位数字的条目。之前处理该表的开发人员错误地将列设置为保存十位数字的条目。我需要将类型从 CHAR(10)
更改为 CHAR(9)
。
按照上面链接的讨论的说明,我写了声明
更改表 [MY_TABLE] 更改列 [MY_COLUMN] CHAR(9);
这将返回错误消息“字符串或二进制数据将被截断”。我看到我的九位数字符串附加了一个空格,使它们成为十位数。
如何告诉 SQL Server 放弃多余的空间并将列转换为 CHAR(9) 类型?
I'm working with MS SQL SERVER 2003. I want to change a column in one of my tables to have fewer characters in the entries. This is identical to this question: Altering a Table Column to Accept More Characters except for the fact that I want fewer characters instead of more.
I have a column in one of my tables that holds nine-digit entries. A developer previously working on the table mistakenly set the column to hold ten-digit entries. I need to change the type from CHAR(10)
to CHAR(9)
.
Following the instructions from the discussion linked above, I wrote the statement
ALTER TABLE [MY_TABLE] ALTER COLUMN [MY_COLUMN] CHAR(9);
This returns the error message "String or binary data would be truncated". I see that my nine-digit strings have a space appended to make them ten digits.
How do I tell SQL Server to discard the extra space and convert my column to a CHAR(9) type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您收到错误是因为该表中的某些值恰好是 10 个字符长(没有尾随空格)。因此,更改表会将这些值削减到长度 9。
默认情况下不允许这样做。如果只有字符串带有一些尾随空格,那就没有问题。
因此,如果您同意删除这些值,请先执行
UPDATE MY_TABLE SET MY_COLUMN = LEFT(MY_COLUMN, 9)
,然后再进行更改。
I think you get the error because there are some values in that table that are exactly 10 chars long (with no trailing spaces). Altering the table would thus cut these values to the length 9.
This is not allowed by default. If there only would be strings which would have some trailing spaces, there would be no problem with that.
So, if you are ok with cutting those values, do
UPDATE MY_TABLE SET MY_COLUMN = LEFT(MY_COLUMN, 9)
first, after that do the alter.
在更改表格之前,请禁用 Ansi 警告。
请注意,如果碰巧有 10 个字符长的数据将会被截断。
编辑
在实际更改列长度之前检查现有长度。
Disable Ansi Warnings before you alter your table.
Beware that data will be truncated if you happen to have something 10 characters long.
Edit
Check existing lengths before actually changing the column length.
上述两个答案对我不起作用,因为我在试图更改的表上附加了一个历史记录表。这就是我所做的:
The above 2 answers didn't work for me because I had a history table attached to the table I was trying to alter. This is what I did: