【问题标题】:Postgresql not truncating overlength stringsPostgresql 不截断超长字符串
【发布时间】:2014-12-01 23:51:18
【问题描述】:

根据documentation,长于字符可变或VARCHAR指定的字符串应该被截断:

如果将一个值显式转换为字符可变(n)或字符(n),那么超长值将被截断为 n 个字符而不会引发错误。 (这也是 SQL 标准所要求的。)

但我无法让它工作。现在文档确实说必须“明确地”将值转换为字符变化,所以也许我错过了这一点。下面是一个简单的测试表:

create table test1(
tval character varying(20));

以下失败并出现错误: value too long for type character varying(20)

insert into test1 values 
('this is a super long string that we want to see if it is really truncated');

我怎样才能让它工作?

【问题讨论】:

  • 什么文档说长字符串会被自动截断?您能否引用相关文档或提供链接? MySQL 做这种事情(取决于它的配置方式),PostgreSQL 更明智。

标签: postgresql sql-insert create-table postgresql-9.3


【解决方案1】:

这不会被截断,因为它只是一个赋值:

create table test1(tval character varying(20));

insert into test1 values ('this is a super long string that we want to see if it is really truncated');

但这会,因为它是一个显式转换:

insert into test1 values (CAST('this is a super long string that we want to see if it is really truncated' AS varchar(20)));

要获得截断行为,您必须使用显式强制转换,坦率地说,我希望 SQL 标准没有指定。

处理这个问题的更好方法是明确说明你想要什么:

insert into test1 values (left('this is a super long string that we want to see if it is really truncated', 20));

【讨论】:

  • 谢谢,这有帮助,因为我不得不在插入之前截断
猜你喜欢
  • 1970-01-01
  • 2011-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-12
  • 2015-07-08
  • 2021-12-22
相关资源
最近更新 更多