SQL Server SQL: How to rename the header using parameter variable?

oxf4rvwz  于 2023-04-19  发布在  其他
关注(0)|答案(1)|浏览(109)

How to rename the header of column 'Q1_2022 to parameter @filteredDate. Below is the working query but don't know how to rename the header '03-31-2022' using @filteredDate. Please suggest.

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);
pengsaosao

pengsaosao1#

There is no way to use dynamic column name at run time, you have to use dynamic sql query, the idea is first you create the query and then execute it like this:

declare @filteredDate Date = '03-31-2022'
declare @query nvarchar(max)

set @query=concat('select ''ColumnCustomHeader'' as [', @filteredDate,']')

EXECUTE sp_executesql @query

SQL Fiddle

You can read more about dynamic query here: https://www.sqlshack.com/dynamic-sql-in-sql-server/

相关问题