将动态表另存为视图/表

时间:2018-05-07 15:34:20

标签: sql sql-server dynamic

我刚刚在这里写了一个脚本,但我不知道如何将它保存为视图或表格。它从行

动态创建列
 DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT  @columns += N', p.' + QUOTENAME([Period])
  FROM (SELECT p.Period FROM dbo.[refv_IRR3_Op_Rev] AS p
  INNER JOIN [dbo].[refv_IRR3_Op_Rev] AS o
  ON p.RMDF = o.RMDF 
  GROUP BY P.Period) AS x;
SET @sql = N'
SELECT [Region]
      ,[LAU]
      ,[RMDF]
      , ' + STUFF(@columns, 1, 2, '') + '
FROM
(
  SELECT [Region]
      ,[LAU]
      ,[RMDF]
      ,[Period]
      ,[Net_Operating_Cashflow]
  FROM [FTTx_Build].[dbo].[refv_IRR3_Op_Rev]

) AS j
PIVOT
(
  SUM([Net_Operating_Cashflow]) FOR Period IN ('
  + STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '')
  + ')
) AS p;';
PRINT @sql;
EXEC sp_executesql @sql;

如何将其另存为视图或表格?

1 个答案:

答案 0 :(得分:1)

简短回答:你做不到。但是,您可以从代码构建存储过程,并在需要这些结果时调用它。