且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL /动态SQL-如果不存在则添加列

更新时间:2023-10-10 21:01:34

列从透视的类别值中得出。只需为金额为NULL的帐户插入虚拟DEF,GHI,ABC类别即可。这些空值不会影响结果,并且如果没有一个帐户具有这些类别,则将生成DEF,GHI,ABC列。

the "columns" derive from the pivoted category values. Just insert dummy DEF, G ABC categories for an account with NULL amount. Those null values will not affect the result and will generate the DEF, G ABC columns if none of the accounts has those categories.

..........................
insert into #temp values ('A004', 'ABC-PR', 1100.00)


insert into #temp(Account, category, amount)
select a.Account, c.category, null
from
(
select top (1) Account from #temp
) as a 
cross join (values('DEF'), ('GHI'), ('ABC'), ('JKL')) AS c(category);

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX);
.........................