我编写了一个动态数据透视图,需要将结果输入临时表,以将结果连接到另一个表。
也许有更好的方法来获得我想要的结果而不插入Temp表?我可以加入Dynamic Pivot中的表来获得我想要的最终结果吗?
获取错误:
Msg 263, Level 16, State 1, Line 59
Must specify table to select from.
Msg 1038, Level 15, State 5, Line 59
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.
我的代码如下:
declare @RealYear as nvarchar(max)
select @RealYear= '2016'
IF OBJECT_ID('tempdb.dbo.#TempCosts', 'U') IS NOT NULL
DROP TABLE #TempCosts;
IF OBJECT_ID('tempdb.dbo.#TempCostsFinal', 'U') IS NOT NULL
DROP TABLE #TempCostsFinal;
select * into #TempCosts from
(
--Journal Entries
select * from lth.dbo.vwJournalEntries_LTWS1
union all
--Non Journal Entries
select *,'' from lth.dbo.vwweeklydebits_ltws1
)D
--select * from #TempCosts
DECLARE @cols AS NVARCHAR(MAX)
declare @query AS NVARCHAR(MAX)
declare @temptable as nvarchar(max)
select @cols = STUFF((SELECT ',', QUOTENAME(AccountRef_FullName)
from #TempCosts
group by AccountRef_FullName
having accountref_Fullname is not null
order by AccountRef_FullName
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT *, ' + @cols + ' from
(
select *
from #TempCosts
where year = ' + @RealYear + '
) x
pivot
(
sum(Amount)
for AccountRef_FullName in (' + @cols + ')
) p
'
execute(@query)
select * into #TempCostsFinal Execute(@query)
答案 0 :(得分:2)
风险很大,因为你冒着碰撞的风险而且效率不高,但你可以将动态结果放到## TempPivot
Set @query = '
IF OBJECT_ID(''tempdb..##TempPivot'') IS NOT NULL
DROP TABLE ##TempPivot
SELECT *,' + @cols + '
Into ##TempPivot
From (
select *
from #TempCosts
where year = ' + @RealYear + '
) x
pivot
(
sum(Amount)
for AccountRef_FullName in (' + @cols + ')
) p
'
Exec(@query)
Select * Into #Temp from ##TempPivot
Drop Table ##TempPivot
答案 1 :(得分:1)
使用适当的设计创建临时表。然后使用以下查询而不是SELECT * INTO
INSERT into #TempCostsFinal
Execute(@query)