如果表存在,我有以下查询,但如果不存在则会出错。
WITH allTables AS (
SELECT
CONCAT(user_dim.app_info.app_id, ':', user_dim.app_info.app_platform) as app,
user_dim.app_info.app_instance_id AS users
FROM `table.app_events_intraday_*`, UNNEST(event_dim) AS event
WHERE _TABLE_SUFFIX BETWEEN '20170406' AND '20170406'
UNION ALL
SELECT
CONCAT(user_dim.app_info.app_id, ':', user_dim.app_info.app_platform) as app,
user_dim.app_info.app_instance_id AS users
FROM `table.app_events_*`, UNNEST(event_dim) AS event
WHERE _TABLE_SUFFIX BETWEEN '20170406' AND '20170406'
)
SELECT
app as target,
COUNT(DISTINCT(users)) AS datapoint_value,
UNIX_SECONDS(PARSE_TIMESTAMP('%Y%m%d', '20170406')) as datapoint_time
FROM allTables
GROUP BY app
此查询根据_TABLE_SUFFIX
选择当前日期/时间范围活动用户。问题是当表不存在时,它会返回以下错误:
错误:项目:table.app_events_intraday_ *与任何表格都不匹配。
我知道这样做是因为该表不存在。我需要找到一种方法来检查表是否存在,然后再查询它。任何帮助都会很棒,谢谢!
答案 0 :(得分:1)
尝试以下
#standardSQL
WITH allTables AS (
SELECT
CONCAT(user_dim.app_info.app_id, ':', user_dim.app_info.app_platform) AS app,
user_dim.app_info.app_instance_id AS users
FROM `table.app_events_*`, UNNEST(event_dim) AS event
WHERE _TABLE_SUFFIX BETWEEN 'intraday_20170406' AND 'intraday_20170406'
UNION ALL
SELECT
CONCAT(user_dim.app_info.app_id, ':', user_dim.app_info.app_platform) AS app,
user_dim.app_info.app_instance_id AS users
FROM `table.app_events_*`, UNNEST(event_dim) AS event
WHERE _TABLE_SUFFIX BETWEEN '20170406' AND '20170406'
)
SELECT
app AS target,
COUNT(DISTINCT(users)) AS datapoint_value,
UNIX_SECONDS(PARSE_TIMESTAMP('%Y%m%d', '20170406')) AS datapoint_time
FROM allTables
GROUP BY app
或者它可以"重构"进入
#standardSQL
WITH allTables AS (
SELECT
CONCAT(user_dim.app_info.app_id, ':', user_dim.app_info.app_platform) AS app,
user_dim.app_info.app_instance_id AS users
FROM `table.app_events_*`, UNNEST(event_dim) AS event
WHERE _TABLE_SUFFIX BETWEEN '20170406' AND '20170406'
OR _TABLE_SUFFIX BETWEEN 'intraday_20170406' AND 'intraday_20170406'
)
SELECT
app AS target,
COUNT(DISTINCT(users)) AS datapoint_value,
UNIX_SECONDS(PARSE_TIMESTAMP('%Y%m%d', '20170406')) AS datapoint_time
FROM allTables
GROUP BY app
答案 1 :(得分:0)
我建议添加名为app_events_intraday_empty的空表,其格式与真实表相同,这样即使实际表不存在,您的查询也不会出错
答案 2 :(得分:0)
检查表是否存在的一种方法(还有更多)(在dbo模式上):
IF EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[YourTableName]') AND [type] in (N'U'))
Begin
--DoSomething
End