根据所选的表参数显示列

时间:2015-01-09 15:00:26

标签: sql-server-2008 tsql reporting-services ssrs-2008-r2

我有一份我正在做的特别报道。用户可以从数据库中选择一个表,然后选择他们想要显示的列。这是我拥有的代码和参数。

SELECT 
    name, TABLE_NAME, COLUMN_NAME  
FROM 
    sys.tables
INNER JOIN  
    INFORMATION_SCHEMA.COLUMNS ON TABLE_NAME = name
WHERE 
    TABLE_NAME = @TableName <--multiselect drop down
    AND COLUMN_NAME = @ColumnName <--multiselect drop down

我的问题是如何在报表上创建列,以便根据选择显示相应的列名。有些表有4列,有些有30列。我已经看到了如何根据选择隐藏列可见性,但是我需要有278列,必须有更好的方法。

感谢。

1 个答案:

答案 0 :(得分:0)

这可以通过两种方式完成。

方法1:将表名作为参数传递,将列名作为逗号分隔值

DECLARE @TableName NVARCHAR(100) = 'Tablename'
DECLARE @ColumnName NVARCHAR(100) = 'Column1,Column2'

SELECT 
    name, TABLE_NAME, COLUMN_NAME  
FROM 
    sys.tables
INNER JOIN  
    INFORMATION_SCHEMA.COLUMNS ON TABLE_NAME = name
WHERE 
TABLE_NAME = @TableName
AND COLUMN_NAME IN
(
    -- Convert Comma Separated Values to rows
    SELECT PARSENAME(REPLACE(Split.a.value('.', 'VARCHAR(100)'),'-','.'),1) 'Columns' 
    FROM  
    (
         SELECT CAST ('<M>' + REPLACE(@ColumnName, ',', '</M><M>') + '</M>' AS XML) AS Data              
    ) AS A 
    CROSS APPLY Data.nodes ('/M') AS Split(a)
)

方法2:将表名作为参数和列名传递到临时表中

DECLARE @TableName NVARCHAR(100) = 'Tablename'    

SELECT 
    name, TABLE_NAME, COLUMN_NAME  
FROM 
    sys.tables
INNER JOIN  
    INFORMATION_SCHEMA.COLUMNS ON TABLE_NAME = name
WHERE 
TABLE_NAME = @TableName 
AND COLUMN_NAME IN
(
    -- Consider you are inserting the column names to a temporary table before executing this query
    SELECT COLS FROM TEMPTABLE
)