Truncate a VARCHAR to specific length in Derby AUTOMATICALLY

半世苍凉 提交于 2020-01-04 07:35:31

问题


How can I truncate a VARCHAR to the table field length AUTOMATICALLY in Derby using SQL?

To be specific:

CREATE TABLE A ( B VARCHAR(2) );
INSERT INTO A B VALUES ('1234');

would throw a SQLException:

A truncation error was encountered trying to shrink VARCHAR '123' to length 2.

Is there a easy way to suppress this exception?


回答1:


No. You should chop it off after checking the meta-data. Or if you don't wanna check the meta-data everytime, then you must keep both your code and database in sync. But thats not a big deal, its a usual practice in validators.




回答2:


You can trim the varchar before inserting it. use the trim function in your insert script/procedure.

I'm not familiar with Derby, but in MSSQL I do exactly the same thing, using trim to avoid truncation error (only where I don't need the full data), it's much more preferable to increase the length of the varchar




回答3:


You can use SUBSTR:

CREATE TABLE A ( B VARCHAR(2) );
INSERT INTO A B VALUES (SUBSTR('1234', 1, 2));

In case you use prepared statements:

INSERT INTO A B VALUES (SUBSTR(?, 1, 2));


来源:https://stackoverflow.com/questions/1016901/truncate-a-varchar-to-specific-length-in-derby-automatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!