如何从含casting的自定义SQL查询(非视图/表)中获取列数据类型
获取自定义SQL查询结果的列数据类型(含CAST场景)
下面是PostgreSQL中几种实用的方法,和pgAdmin4的底层逻辑类似:
方法1:用pg_typeof()直接在查询中返回类型
在查询语句里,给每个需要确认类型的列添加pg_typeof(列名)的字段,直接返回该列的数据类型:
SELECT user_id, pg_typeof(user_id) AS user_id_type, CAST(register_time AS DATE) AS register_date, pg_typeof(CAST(register_time AS DATE)) AS register_date_type FROM users;
执行后就能在结果里同时看到列值和对应的类型。
方法2:通过EXPLAIN (FORMAT JSON)解析查询计划
PostgreSQL的查询计划会包含输出列的详细类型信息,用JSON格式输出后可以直接查看:
EXPLAIN (FORMAT JSON) SELECT order_id, CAST(total_amount AS NUMERIC(12,2)) AS formatted_total, CONCAT('ORD-', order_id) AS order_code FROM orders;
查看返回的JSON结果,找到Output字段,里面会列出每个输出列的完整类型,比如:
"Output": ["order_id integer", "formatted_total numeric(12,2)", "order_code text"]
方法3:临时视图+系统表查询(会话级临时对象,无持久化影响)
如果需要结构化的类型列表,可以创建临时视图(会话结束自动销毁,不会污染数据库),再查询information_schema.columns获取类型:
-- 创建临时视图存储查询结果结构 CREATE TEMP VIEW temp_query_schema AS SELECT product_id, CAST(stock_count AS SMALLINT) AS small_stock, CAST(price AS REAL) AS price_real FROM products; -- 查询临时视图的列类型 SELECT column_name, data_type, udt_name FROM information_schema.columns WHERE table_name = 'temp_query_schema';
内容的提问来源于stack exchange,提问作者UnderCode
相关产品推荐
相关产品推荐

