PL/SQL varchar(10) 到 varchar(9)
我将如何编写一个循环,在循环的“in”子句中有一个 select,选择 varchar(10)
类型的 col,然后将这些值插入到希望它们成为的 col 中varchar(9)
?基本上,我正在尝试从一种精度“类型转换”到另一种精度,如果这有意义的话。示例:
FOR V_TEN IN (SELECT THIS_IS_VARCHAR_TEN FROM TABLE WHERE SOMETHING=’VALUE’)
LOOP
INSERT INTO OTHER_TABLE
(THIS_IS_VARCHAR_NINE)
VALUES
(V_TEN);
END LOOP;
错误是列类型不相同。我尝试查看 to_char()
和 cast()
但似乎都不是我想要的。我意识到这里存在精度损失,但我对此表示同意,因为我实际上知道 varchar(10)
列中的值始终为 9 个字符。
How would I write a loop that has a select in the “in” clause of the loop that selects a col of type varchar(10)
, but then inserts those values in a col that wants them to be varchar(9)
? Basically I’m trying to “typecast” from one precision to another, if that makes any sense. Example:
FOR V_TEN IN (SELECT THIS_IS_VARCHAR_TEN FROM TABLE WHERE SOMETHING=’VALUE’)
LOOP
INSERT INTO OTHER_TABLE
(THIS_IS_VARCHAR_NINE)
VALUES
(V_TEN);
END LOOP;
The error is that the column types aren’t the same. I’ve tried looking at to_char()
and cast()
but neither seem to be what I want. I realize there is a loss of precision here and am okay with that, since I actually know that the values in the varchar(10)
column are always going to be 9 chars.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找 SUBSTR 函数。
另外,不要为此使用 PL/SQL,普通 SQL 就可以,而且速度更快。
如果确实没有超过九个字符的值,您甚至不需要调用 substr 函数(它将自动转换,如果太长会引发错误)。
You are looking for the SUBSTR function.
Also, do not use PL/SQL for this, plain SQL will do and be faster.
And if there are really no values longer than nine character, you do not even need to call the substr function (it will be converted automatically, and raise an error if too long).
如果这是真的,那么您甚至不需要像其他人建议的那样使用 SUBSTR。
我相信您收到错误的原因是您试图插入 V_TEN 的值。当您使用像
FOR x IN (SELECT ...) LOOP
这样的构造时,x
被隐式声明为记录类型。在您的情况下,它是一条只有一个字段的记录,但您仍然不能直接将其用作标量类型。您只需在插入中按名称引用记录字段即可。
无论如何,正如 Thilo 指出的那样,根本没有理由在显式循环中执行此操作。只需将其写为单个 INSERT ... SELECT 即可。
If that's true, then you don't even need to use SUBSTR as others have been suggesting.
I believe the reason that you're getting an error is that you are trying to insert the value of V_TEN. When you use a construct like
FOR x IN (SELECT ...) LOOP
,x
is implicitly declared as a record type. In your case, it's a record with only one field, but you still can't use it directly as a scalar type.You just need to reference the field of the record by name in your insert.
In any case, as Thilo pointed out, there's no reason to do this in an explicit loop at all. Just write it as a single INSERT ... SELECT.
使用:
使用 SUBSTR 函数对 VARCHAR(10) 数据进行子字符串化,以便将其返回作为 VARCHAR(9)
Use:
Use the SUBSTR function to substring the VARCHAR(10) data so it is returned as VARCHAR(9)