简体   繁体   English

无法在 Big Query 中更改列数据类型

[英]Unable to alter column data type in Big Query

We imported database into BigQuery but a lot of columns are not in correct data types, many of them are stored as STRING.我们将数据库导入 BigQuery,但很多列的数据类型不正确,其中许多列存储为 STRING。 I want to fix them by change the data type in BigQuery我想通过更改 BigQuery 中的数据类型来修复它们

ALTER TABLE my.data_set.my_table ALTER COLUMN create_date SET DATA TYPE DATE;

But I got但我得到了

ALTER TABLE ALTER COLUMN SET DATA TYPE requires that the existing column type (STRING) is assignable to the new type (DATE)

How to solve it?如何解决?

Unfortunately, as far as I know there is no way to convert data type from STRING to DATE using ALTER TABLE but to create it again with the schema you want.不幸的是,据我所知,没有办法使用ALTER TABLE将数据类型从STRING转换为DATE ,而是使用您想要的模式再次创建它。

CREATE OR REPLACE TABLE testset.tbl AS 
SELECT 'a' AS col1, '2022-05-16' AS create_date
 UNION ALL
SELECT 'a' AS col1, '2022-05-14' AS create_date
;

-- ALTER TABLE testset.tbl ALTER COLUMN create_date SET DATA TYPE DATE;

-- Query error: ALTER TABLE ALTER COLUMN SET DATA TYPE requires that
-- the existing column type (STRING) is assignable to the new type (DATE) at [7:25]


-- Create it again. 
CREATE OR REPLACE TABLE testset.tbl AS
SELECT * REPLACE(SAFE_CAST(create_date AS DATE) AS create_date) 
  FROM testset.tbl;

Follow the steps below:请按照以下步骤操作:

  1. Rename the existing column重命名现有列
ALTER TABLE mydataset.mytable RENAME COLUMN create_date TO create_date_to_drop;
  1. Add the column with the required data type.添加具有所需数据类型的列。
 ALTER TABLE mydataset.mytable ADD COLUMN create_date DATE;
  1. Drop the renamed column.删除重命名的列。
 ALTER TABLE mydataset.mytable DROP COLUMN create_date_to_drop;

Note: As of now, DROP COLUMN won't work on the tables protected by customer-managed encryption keys.注意:截至目前,DROP COLUMN 不适用于受客户管理的加密密钥保护的表。

Alternatively, you can drop the existing column in the beta version and add it with the new data type, but you need to wait until the time travel window (7 days by default) to get over for adding the column with the same name.或者,您可以删除 beta 版本中的现有列并使用新数据类型添加它,但是您需要等到时间旅行window(默认为 7 天)才能结束添加具有相同名称的列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM