gpt4 book ai didi

Postgresql 不截断超长字符串

转载 作者:行者123 更新时间:2023-11-29 11:32:50 28 4
gpt4 key购买 nike

根据documentation , 比 character varying 或 VARCHAR 指定的字符串长的字符串应该被截断:

If one explicitly casts a value to character varying(n) or character(n), then an over-length value will be truncated to n characters without raising an error. (This too is required by the SQL standard.)

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

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

以下失败并显示错误:对于类型字符 varying(20) 值太长

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

我怎样才能让它工作?

最佳答案

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

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

关于Postgresql 不截断超长字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27239523/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com