动态SQL查询案例
需求描述:
原始的表名、表的属性描述信息在summary表中,每个表有类似的字段:id、price、size,通过SQL能查询到所有表的如下记录: 表名、表属性名、最低价格、最低价格对应ID、最大尺寸、最大尺寸对应ID。
解决方法:
-- 1 定义表并初始化数据(支持ROW_NUMBER的SQL Server、Oracle、MariaDB、Mysql 8、Doris、Hive、Impala等)
CREATE TABLE apple (
ID int,
price int,
size int
);
CREATE TABLE banana (
ID int,
price int,
size int
) ;
CREATE TABLE summary (
id int,
table_name varchar(30),
table_desc varchar(30)
) ;
INSERT INTO apple(ID, price, size) VALUES (1, 30, 9);
INSERT INTO apple(ID, price, size) VALUES (2, 10, 4);
INSERT INTO apple(ID, price, size) VALUES (3, 40, 6);
INSERT INTO banana(ID, price, size) VALUES (20, 8, 10);
INSERT INTO banana(ID, price, size) VALUES (21, 15, 24);
INSERT INTO summary(id, table_name, table_desc) VALUES (1, 'APPLE', '苹果');
INSERT INTO summary(id, table_name, table_desc) VALUES (2, 'BANANA', '香蕉');
-- 2 定义动态SQL,可以再封装成存储过程
DECLARE @sql varchar(6000)
set @sql = ''
select @sql = @sql +'SELECT '+''''+TABLE_NAME+''''+' TABLE_NAME,'+''''+TABLE_DESC+''''+' TABLE_DESC' + ',min(min_price) min_price,
min(price_id_rn) min_price_id,
min(max_size) max_size,
min(size_id_rn) max_size_id
FROM
(
SELECT MIN(PRICE)OVER(ORDER BY (SELECT 1)) min_price,
CASE WHEN ROW_NUMBER()OVER(ORDER BY price ASC) = 1 THEN ID ELSE NULL END price_id_rn,
MAX(SIZE)OVER(ORDER BY (SELECT 1)) max_size,
CASE WHEN ROW_NUMBER()OVER(ORDER BY size DESC)=1 THEN ID ELSE NULL END size_id_rn
FROM '
+ table_name
+ ')B UNION ALL ' from SUMMARY
set @sql = SUBSTRING(@sql,1,LEN(@sql)-10)
-- SELECT @sql
EXEC( @sql)