更新时间:2022-07-12 GMT+08:00

类型转换函数

语法格式

CAST(value AS type)

语法说明

类型强制转换。

注意事项

若输入为NULL,则返回NULL。

示例

将amount值转换成整型。

insert into temp select cast(amount as INT) from source_stream;
表1 类型转换函数示例

示例

说明

示例

cast(v1 as string)

将v1转换为字符串类型,v1可以是数值类型,TIMESTAMP/DATE/TIME。

表T1:

| content (INT)           |
| -------------           |
| 5                       |

语句:

SELECT
  cast(content as varchar)
FROM
  T1;

结果:

"5"

cast (v1 as int)

将v1转换为int, v1可以是数值类型或字符类。

表T1:

| content  (STRING)           |
| -------------               |
| "5"                         |

语句:

SELECT
  cast(content as int)
FROM
  T1;

结果:

5

cast(v1 as timestamp)

将v1转换为timestamp类型,v1可以是字符串或DATE/TIME。

表T1:

| content  (STRING)          |
| -------------              |
| "2018-01-01 00:00:01"     |

语句:

SELECT
  cast(content as timestamp)
FROM
  T1;

结果:

1514736001000

cast(v1 as date)

将v1转换为date类型, v1可以是字符串或者TIMESTAMP。

表T1:

| content  (TIMESTAMP)     |
| -------------            |
| 1514736001000            |

语句:

SELECT
  cast(content as date)
FROM
  T1;

结果:

"2018-01-01"

Flink作业不支持使用CAST将“BIGINT”转换为“TIMESTAMP”,可以使用to_timestamp进行转换。

详细样例代码

/** source **/
CREATE
TABLE car_infos (cast_int_to_string int, cast_String_to_int string,
case_string_to_timestamp string, case_timestamp_to_date timestamp(3)) WITH (
  'connector.type' = 'dis',
  'connector.region' = 'xxxxx',
  'connector.channel' = 'dis-input',
  'format.type' = 'json'
);
/** sink **/
CREATE
TABLE cars_infos_out (cast_int_to_string string, cast_String_to_int
int, case_string_to_timestamp timestamp(3), case_timestamp_to_date date) WITH (
  'connector.type' = 'dis',
  'connector.region' = 'xxxxx',
  'connector.channel' = 'dis-output',
  'format.type' = 'json'
);
/** 统计car的静态信息 **/
INSERT
INTO
  cars_infos_out
SELECT
  cast(cast_int_to_string as string),
  cast(cast_String_to_int as int),
  cast(case_string_to_timestamp as timestamp),
  cast(case_timestamp_to_date as date)
FROM
  car_infos;