A função CAST do MaxCompute converte o resultado de uma expressão em um tipo de dados de destino. Este tópico descreve o formato do comando, os parâmetros e exemplos de uso da função CAST.
Formato do comando
cast(<expr> as <type>)
Descrição dos parâmetros
expr: Obrigatório. Os dados source a converter.
type: Obrigatório. O tipo de dados de destino. Uso:
cast(double as bigint): Converte um valor DOUBLE em BIGINT.cast(string as bigint): Converte uma string em um valor BIGINT. Se a string representar um número inteiro, a conversão será direta. Caso represente um número de ponto flutuante ou em notação científica, a conversão ocorrerá primeiro para o tipo DOUBLE e depois para BIGINT.cast(string as datetime)oucast(datetime as string): Usa o formato de data padrãoyyyy-mm-dd hh:mi:ss.-
Conversão entre tipos de dados básicos e tipos JSON.
A função cast também aceita conversões entre o tipo JSON e tipos de dados básicos, incluindo JSON, STRING, BIGINT, INT, TINYINT, SMALLINT, DOUBLE, FLOAT, BOOLEAN e
SQL-TYPE. Exemplos de comandos:cast(json as string): Converte uma expressão JSON no tipo STRING. A expressão JSON não pode ser ARRAY ou OBJECT.cast(string as json): Converte um valor STRING em uma expressão JSON do tipo STRING. Esse comportamento difere dejson_parseejson_format. Ojson_parsetransforma uma string JSON válida em um valor JSON, que pode ser um OBJECT JSON. Já ocast(string as json)converte qualquer string em uma string JSON.cast(null as json): Converte um valor NULL no tipo JSON.cast(json 'null' as ...):json 'null'enullsão convertidos emnullSQL.
Descrição do valor de retorno
Retorna um valor do tipo de dados de destino.
Se você executar
setproject odps.function.strictmode=false, a função retornará os números anteriores a quaisquer letras.Se você executar
setproject odps.function.strictmode=true, a função retornará um erro.-
Ao converter um valor no tipo Decimal:
Se você definir
odps.sql.decimal.tostring.trimzero=true, os zeros à direita após o ponto decimal serão removidos.-
Se você definir
odps.sql.decimal.tostring.trimzero=false, os zeros à direita após o ponto decimal serão mantidos.ImportanteO parâmetro
odps.sql.decimal.tostring.trimzeroafeta tanto os dados recuperados de tabelas quanto valores estáticos.
Exemplos de uso
-
Exemplo 1: Uso comum.
--Returns 1. select cast('1' as bigint); -
Exemplo 2: Conversão de um valor STRING em BOOLEAN. Se a STRING estiver vazia, o retorno será
false. Caso contrário, serátrue.-
STRING vazia.
select cast("" as boolean); --Returns +------+ | _c0 | +------+ | false | +------+ -
STRING não vazia.
select cast("false" as boolean); --Returns true +------+ | _c0 | +------+ | true | +------+
-
-
Exemplo 3: Conversão de string em data.
--Convert a string to a date. select cast("2022-12-20" as date); --Returns +------------+ | _c0 | +------------+ | 2022-12-20 | +------------+ --Convert a date string with a time part to a date. select cast("2022-12-20 00:01:01" as date); --Returns +------------+ | _c0 | +------------+ | NULL | +------------+ --To ensure the value is displayed correctly, set the following parameter: set odps.sql.executionengine.enable.string.to.date.full.format= true; select cast("2022-12-20 00:01:01" as date); --Returns +------------+ | _c0 | +------------+ | 2022-12-20 | +------------+NotaPor padrão, o parâmetro
odps.sql.executionengine.enable.string.to.date.full.formatéfalse. Para converter uma string de data que inclui a parte de hora, defina este parâmetro comotrue. -
Exemplo 4 (Exemplo de comando incorreto): Uso inválido. Uma exceção será lançada se a conversão falhar ou não tiver suporte. O comando a seguir é um exemplo de uso incorreto.
select cast('abc' as bigint); -
Exemplo 5: Cenário com
setproject odps.function.strictmode=falsedefinido.setprojectodps.function.strictmode=false; select cast('123abc'as bigint); --Returns +------------+ |_c0| +------------+ |123| +------------+ -
Exemplo 6: Cenário com
setproject odps.function.strictmode=truedefinido.setprojectodps.function.strictmode=true; select cast('123abc' as bigint); --Returns FAILED:ODPS-0130071:[0,0]Semanticanalysisexception-physicalplangenerationfailed:java.lang.NumberFormatException:ODPS-0123091:Illegaltypecast-Infunctioncast,value'123abc'cannotbecastedfromStringtoBigint. -
Exemplo 7: Cenário com
odps.sql.decimal.tostring.trimzerodefinido.--Create a table. create table mf_dot (dcm1 decimal(38,18), dcm2 decimal(38,18)); --Insert data. insert into table mf_dot values (12.45500BD,12.3400BD); --When the flag is true or not set. set odps.sql.decimal.tostring.trimzero=true; --Remove trailing zeros after the decimal point. select cast(round(dcm1,3) as string),cast(round(dcm2,3) as string) from mf_dot; --Return value +------------+------------+ | _c0 | _c1 | +------------+------------+ | 12.455 | 12.34 | +------------+------------+ --When the flag is false. set odps.sql.decimal.tostring.trimzero=false; --Keep trailing zeros after the decimal point. select cast(round(dcm1,3) as string),cast(round(dcm2,3) as string) from mf_dot; --Return value +------------+------------+ | _c0 | _c1 | +------------+------------+ | 12.455 | 12.340 | +------------+------------+ --This parameter also applies to static values. set odps.sql.decimal.tostring.trimzero=false; select cast(round(12345.120BD,3) as string); --Returns: +------------+ | _c0 | +------------+ | 12345.120 | +------------+
-
Exemplo 8: Conversão entre tipos STRING e JSON.
--Convert JSON to string. select cast(json '123' as string); --Returns: +-----+ | _c0 | +-----+ | 123 | +-----+ --Convert JSON to string. select cast(json '"abc"' as string); --Returns: +-----+ | _c0 | +-----+ | abc | +-----+ --Convert JSON to string. select cast(json 'true' as string); --Returns: +-----+ | _c0 | +-----+ | TRUE | +-----+ --Convert JSON to string. select cast(json 'null' as string); --Returns: +-----+ | _c0 | +-----+ | NULL | +-----+ --Convert string to JSON. select cast('{"a":2}' as json); --Returns: +-----+ | _c0 | +-----+ | "{\"a\":2}" | +-----+ --Incorrect example of converting JSON to string. Converting JSON expressions of the ARRAY or OBJECT type to string is not supported. select cast(json '{"a":2}' as string); --An error is returned: FAILED: ODPS-0123091:Illegal type cast - Unsupported cast from json array/object to string -
Exemplo 9: Conversão entre tipos NUMBER e JSON.
--Convert JSON to bigint. select cast(json '123' as bigint); --Returns: +------------+ | _c0 | +------------+ | 123 | +------------+ --Convert JSON to float. select cast(json '"1.23"' as float); --Returns: +------+ | _c0 | +------+ | 1.23 | +------+ --Convert JSON to double. select cast(json '1.23' as double); --Returns: +------------+ | _c0 | +------------+ | 1.23 | +------------+ --Convert int to JSON. select cast(123 as json); --Returns: +-----+ | _c0 | +-----+ | 123 | +-----+ --Convert float to JSON. select cast(1.23 as json); --Returns: +-----+ | _c0 | +-----+ | 1.23 | +-----+ -
Exemplo 10: Conversão entre tipos BOOLEAN e JSON.
--Convert boolean to JSON. select cast(true as json); --Returns: +-----+ | _c0 | +-----+ | true | +-----+ --Convert JSON to boolean. select cast(json 'false' as boolean); --Returns: +------+ | _c0 | +------+ | false | +------+ --Convert JSON to boolean. select cast(json '"abc"' as boolean); --Returns: +------+ | _c0 | +------+ | true | +------+ --ARRAY or OBJECT cannot be converted to boolean. select cast(json '[1,2]' as boolean); --An error is returned: Unsupported cast from json array/object to boolean -
Exemplo 11: Conversão entre tipos NULL e JSON.
--Convert null to JSON. select json_type(cast(null as json)); --Returns: +-----+ | _c0 | +-----+ | NULL | +-----+
Funções relacionadas
A função CAST é uma função de tipo complexo. Para obter mais informações sobre funções que processam tipos de dados complexos, como ARRAY, MAP, STRUCT e JSON, consulte Complex type functions.
A função CAST também pertence a outra categoria de funções. Para obter mais detalhes sobre funções para outros cenários de negócios, consulte Other functions.