文档首页/
数据湖探索 DLI/
SQL语法参考(即将下线)/
历史版本(即将下线)/
Flink SQL语法参考(不再演进,推荐使用Flink OpenSource SQL)/
内置函数/
类型转换函数
更新时间:2024-07-27 GMT+08:00
类型转换函数
语法格式
CAST(value AS type)
语法说明
类型强制转换。
注意事项
- 若输入为NULL,则返回NULL。
- Flink作业不支持使用CAST将“BIGINT”转换为“TIMESTAMP”,可以使用to_timestamp或者to_localtimestamp进行转换。
示例
将amount值转换成字符串,长度为转换后的实际长度,配置的长度无效。
insert into temp select cast(amount as VARCHAR(10)) from source_stream;
常用类型转换函数
函数 |
说明 |
---|---|
将v1转换为字符串类型,v1可以是数值类型,TIMESTAMP/DATE/TIME。 |
|
将v1转换为int, v1可以是数值类型或字符类。 |
|
将v1转换为timestamp类型,v1可以是字符串或DATE/TIME。 |
|
将v1转换为date类型, v1可以是字符串或者TIMESTAMP。 |
- cast(v1 as varchar)
- 测试语句:
SELECT cast(content as varchar) FROM T1;
- 测试数据和结果
表2 T1 content(INT)
varchar
5
"5"
- 测试语句:
- cast (v1 as int)
- 测试语句:
SELECT cast(content as int) FROM T1;
- 测试数据和结果
表3 T1 content(STRING)
int
"5"
5
- 测试语句:
- cast(v1 as timestamp)
- 测试语句:
SELECT cast(content as timestamp) FROM T1;
- 测试数据和结果
表4 T1 content(STRING)
timestamp
"2018-01-01 00:00:01"
1514736001000
- 测试语句:
- cast(v1 as date)
- 测试语句:
SELECT cast(content as date) FROM T1;
- 测试数据和结果
表5 T1 content(TIMESTAMP)
date
1514736001000
"2018-01-01"
- 测试语句:
详细样例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
/** source **/ CREATE SOURCE STREAM car_infos (cast_int_to_varchar int, cast_String_to_int string, case_string_to_timestamp string, case_timestamp_to_date timestamp) WITH ( type = "dis", region = "xxxxx", channel = "dis-input", partition_count = "1", encode = "json", offset = "13", json_config = "cast_int_to_varchar=cast_int_to_varchar;cast_String_to_int=cast_String_to_int;case_string_to_timestamp=case_string_to_timestamp;case_timestamp_to_date=case_timestamp_to_date" ); /** sink **/ CREATE SINK STREAM cars_infos_out (cast_int_to_varchar varchar, cast_String_to_int int, case_string_to_timestamp timestamp, case_timestamp_to_date date) WITH ( type = "dis", region = "xxxxx", channel = "dis-output", partition_count = "1", encode = "json", offset = "4", json_config = "cast_int_to_varchar=cast_int_to_varchar;cast_String_to_int=cast_String_to_int;case_string_to_timestamp=case_string_to_timestamp;case_timestamp_to_date=case_timestamp_to_date", enable_output_null="true" ); /** 统计car的静态信息 **/ INSERT INTO cars_infos_out SELECT cast(cast_int_to_varchar as varchar), cast(cast_String_to_int as int), cast(case_string_to_timestamp as timestamp), cast(case_timestamp_to_date as date) FROM car_infos; |
返回数据
{"case_string_to_timestamp":1514736001000,"cast_int_to_varchar":"5","case_timestamp_to_date":"2018-01-01","cast_String_to_int":100}
父主题: 内置函数