如何更改 Oracle Select 中的日期类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4667586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 22:25:14  来源:igfitidea点击:

How to change the date type in a Oracle Select?

oracletypes

提问by André

I'm usualy use PostgreSQL, but I'm currently doing it in Oracle.

我通常使用 PostgreSQL,但我目前在 Oracle 中使用它。

I need to chage the data type of a column in a query(select), in PostgreSQL I usualy do it in this way:

我需要在查询(选择)中更改列的数据类型,在 PostgreSQL 中我通常这样做:

select 1::varchar from table

Hoe can I do this in Oracle?

我可以在 Oracle 中执行此操作吗?

Best Regards,

此致,

回答by Michael Pakhantsov

convert to varchar

转换为 varchar

 select to_char(Field) from table

truncate varchar

截断 varchar

 select substr(field, 1, 1) from table

回答by Allan

As @Michael Pakhantsov points out, to_charworks for converting to string. Likewise, to_dateand to_timestampare the standard when converting strings to dates and timestamps respectively. However, if you find that you need to perform a more exotic conversion (varchar2 to raw, for instance), then castis your friend:

正如@Michael Pakhantsov 指出的,to_char适用于转换为字符串。同样,to_dateto_timestamp分别是将字符串转换为日期和时间戳时的标准。但是,如果您发现需要执行更奇特的转换(例如,从 varchar2 到 raw),那么cast您的朋友:

Number to string:

数字到字符串:

select cast(field as varchar2(30)) from table;

String to Raw:

字符串到原始:

select cast(field as raw(16)) from table;

回答by mach128x

Like @Allan I like to use cast(), as it can go from and to many types.
However, as the official documentation says,

像@Allan 一样,我喜欢使用cast(),因为它可以转换为多种类型。
但是,正如官方文档所说,

CAST does not support LONG, LONG RAW, any of the LOB datatypes, or the Oracle-supplied types

CAST 不支持 LONG、LONG RAW、任何 LOB 数据类型或 Oracle 提供的类型

So it cannot be used to convert to CLOB, for example, Oracle will throw

所以不能用来转换为CLOB,比如Oracle会抛出

ORA-00932: inconsistent datatypes: expected - got CLOB

ORA-00932: 不一致的数据类型:预期 - 得到 CLOB