PostgreSQL不截断过长的字符串

4
根据文档,超过字符变量或VARCHAR指定长度的字符串应进行截断:

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

但我无法使其正常工作。现在文档确实说必须“显式”将一个值转换为character varying,因此可能我错过了这一点。下面是一个简单的测试表:
create table test1(
tval character varying(20));

以下内容无法执行,出现ERROR: 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');

我该如何让这个工作起来?


5
有哪些文件表明长字符串将被自动截断?你能引用相关文档或提供链接吗?MySQL会这样做(取决于配置方式),而PostgreSQL则更为明智。 - mu is too short
2个回答

7

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

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));

谢谢,那很有帮助,因为我在插入之前必须截断。 - WraithWireless

0

还有另一种解决方案,即在创建列时不指定n: 如果您希望存储没有特定上限的长字符串,请使用没有长度说明符的文本或字符变量,而不是制定任意长度限制。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接