我想从下表中选择Jasper报告的数据。
DDL + DML
CREATE TABLE SLPAYROLL_LIVE.dbo.AA_COLUMN_NAMES(
id int PRIMARY KEY NOT NULL,
name varchar(500) NOT NULL,
active bit
);
INSERT INTO SLPAYROLL_LIVE.dbo.AA_COLUMN_NAMES (id, name, active) VALUES (1, 'col_1', 1);
INSERT INTO SLPAYROLL_LIVE.dbo.AA_COLUMN_NAMES (id, name, active) VALUES (2, 'col_2', 1);
INSERT INTO SLPAYROLL_LIVE.dbo.AA_COLUMN_NAMES (id, name, active) VALUES (3, 'col_3', 1);
INSERT INTO SLPAYROLL_LIVE.dbo.AA_COLUMN_NAMES (id, name, active) VALUES (4, 'col_4', 0);
CREATE TABLE SLPAYROLL_LIVE.dbo.AA_PAYMENT_DETAILS(
id int PRIMARY KEY NOT NULL,
username varchar(500),
col_1 varchar(500),
col_2 varchar(500),
col_3 varchar(500),
col_4 varchar(500)
);
INSERT INTO SLPAYROLL_LIVE.dbo.AA_PAYMENT_DETAILS (id, username, col_1, col_2, col_3, col_4) VALUES (1, 'chathura', '500', '200', '300', '0');
INSERT INTO SLPAYROLL_LIVE.dbo.AA_PAYMENT_DETAILS (id, username, col_1, col_2, col_3, col_4) VALUES (2, 'gihan', '300', '100', '100', '0');
我只想从AA_PAYMENT_DETAILS
中选择活动列。活动列的名称可以从AA_COLUMN_NAMES
表中获取。
我已经搜索了我的问题并找到了以下解决方案。
Select columns from one table based on the column names from another table
由于我想在Jasper Report中使用该查询,因此上述解决方案不起作用。有人知道解决方案吗?
答案 0 :(得分:1)
您必须使用动态SQL来执行此操作-这是一种相当简单的方法:
DECLARE @SQL nvarchar(4000) = '';
SELECT @SQL = @SQL +', '+ name
FROM dbo.AA_COLUMN_NAMES
WHERE active = 1
SET @SQL = 'SELECT id, username' + @SQL + ' FROM dbo.AA_PAYMENT_DETAILS'
EXEC(@SQL)