Postgresql没有截断超长字符串

Wra*_*ess 4 postgresql create-table sql-insert postgresql-9.3

根据文档,字符串变量或VARCHAR指定的字符串应该被截断:

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

但我无法让它发挥作用.现在文档确实说必须"明确地"将值赋予字符变化,所以也许我错过了.下面是一个简单的测试表:

create table test1(
tval character varying(20));
Run Code Online (Sandbox Code Playgroud)

其中以下内容因ERROR而失败:类型字符变化的值太长(20)

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

我怎样才能让它发挥作用?

Cra*_*ger 6

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

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');
Run Code Online (Sandbox Code Playgroud)

但这会,因为它是一个明确的演员:

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

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

处理此问题的更好方法是明确您想要的内容:

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