SQL:如何使用参数变量重命名标题?



如何将列'Q1_2022 '的标题重命名为参数@filteredDate。下面是工作查询,但不知道如何使用@filteredDate重命名标题"03-31-2022"。请建议。

declare @filteredDate Date = '03-31-2022'
select *
from
(SELECT 'BSA' as tabs, ' xyz' as Type, ColumnName AS 'Report',
ColumnValue AS 'Q1_2022'
FROM
(
SELECT
SUM(CAST(col1 AS BIGINT)) AS col1_,
SUM(CAST(col2 AS BIGINT)) AS col2_
FROM [dbo].[table1] table1
FULL OUTER JOIN [dbo].[table2] table2 ON table1.ID = table2.ID
WHERE table5.Institution = '100_bank'
and FileDate = @filteredDate
) p
UNPIVOT
(
ColumnValue FOR ColumnName IN (col1_ , col2_)) unpiv);

没有办法在运行时使用动态列名,你必须使用动态sql查询,这个想法是首先你创建查询,然后像这样执行:

declare @filteredDate Date = '03-31-2022'
declare @query nvarchar(max)
set @query=concat('select ''ColumnCustomHeader'' as [', @filteredDate,']')

EXECUTE sp_executesql @query

SQL小提琴

你可以在这里阅读更多关于动态查询:https://www.sqlshack.com/dynamic-sql-in-sql-server/

相关内容

  • 没有找到相关文章

最新更新