Databricks集群与SQL Warehouse执行建表SQL列类型不一致问题咨询
问题解答
这不是预期行为,核心原因是Spark SQL(集群环境)与Databricks SQL Warehouse的类型推断逻辑存在差异:
差异根源
在你的SQL代码中,coalesce(id,'-1')、coalesce(created_date,'2024-12-11')这类调用存在参数类型不匹配的情况:
- 集群环境基于Spark 3.5.0,
coalesce函数严格遵循类型提升规则:当参数类型不一致时,会自动提升到所有参数的最小共同兼容类型。比如int与string的最小共同类型是string,date与string同理,因此生成的列会被转为字符串类型。 - Databricks SQL Warehouse的SQL引擎做了智能优化,它能识别到字符串字面量可以转换为对应强类型(如
'-1'可转为int、'2024-12-11'可转为date),因此会将结果列推断为第一个参数的原类型(int/date)。
统一行为的解决方案
为了让两种环境下的列类型保持一致,需要显式转换coalesce的第二个参数类型,确保所有参数类型匹配:
create or replace table [catalog].[schema].[test_table_name] using delta comment 'This has a comment' as select id, name as new_name, created_date as new_created_date, current_timestamp() as test_timestamp, coalesce(name,'Replaced name') as test_coalesce_name, coalesce(id, cast('-1' as int)) as test_coalesce_id, -- 显式转换为int coalesce(created_date, cast('2024-12-11' as date)) as test_coalesce_date -- 显式转换为date from ( select cast(col1 as int) as id, cast(col2 as string) as name, cast(col3 as date) as created_date from VALUES (1, 'Alice', '2024-12-01'), (2, 'Bob', '2024-12-02'), (3, 'Charlie', '2024-12-03'), (4, 'David', '2024-12-04'), (5, 'Eve', '2024-12-05'), (6, 'Frank', '2024-12-06'), (7, 'Grace', '2024-12-07'), (8, 'Hank', '2024-12-08'), (9, 'Ivy', '2024-12-09'), (10, 'Jack', '2024-12-10'), (11, NULL, '2024-12-11'), (NULL, 'NULL Values', NULL) ) as temp_table
内容的提问来源于stack exchange,提问作者blobbles
相关产品推荐
相关产品推荐

