----------dynamically unpivot production
DECLARE @colsUnpivot AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
USE [XXXXXX];
with tbl_metric_date_name as(
SELECT distinct '['+ c.name+ ']' AS 'ColumnName'
FROM sys.columns c JOIN sys.tables t ON c.object_id = t.object_id
WHERE t.name ='OH_Oil_Output$' and c.name <> 'API'
)
SELECT distinct @colsUnpivot = STUFF((
SELECT ',' + ColumnName
FROM tbl_metric_date_name
FOR XML PATH ('')
), 1, 1, '')
FROM tbl_metric_date_name;
set @query =
'IF OBJECT_ID(''dbo.temp_OH_Oil_Prod'',''U'') IS NOT NULL DROP TABLE dbo.temp_OH_Oil_Prod
SELECT API, cast(metric_date as date) as metric_date, [value]
INTO dbo.temp_OH_Oil_Prod
FROM [XXXXXX].[dbo].[OH_Oil_Output$] WITH(NOLOCK)
Unpivot
([value] FOR metric_date in ( ' + @colsUnpivot + '))u'
exec sp_executesql @query;
No comments:
Post a Comment