Insert into Temp Table from SQL Dynamic Results - sql

I am trying to insert the result of the sql dynamic into a temp table but i am getting a syntax error. I have researched and i am not able to figure what i am doing wrong here
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName = ISNULL(#ColumnName + ',','') + QUOTENAME([month])
FROM (SELECT DISTINCT [Month] FROM MyTable) AS [Month]
order by [month]
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT Mem_Name, ' + #ColumnName + '
FROM MyTable into MyTest
PIVOT(SUM(Amount)
FOR Month IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery

all what i had to do is add this:
' into ##myTempTable
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName = ISNULL(#ColumnName + ',','') + QUOTENAME([month])
FROM (SELECT DISTINCT [Month] FROM MyTable) AS [Month]
order by [month]
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT Mem_Name, ' + #ColumnName + ' into ##myTempTable
FROM MyTable
PIVOT(SUM(Amount)
FOR Month IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery

Related

How to pivot Weekend Dates as column dynamically in SQL

I have a #temp table output, which I am trying to bring the weekend dates as columns.
When I run the query I get this error "Parse error at line: 5, column: 34: Incorrect syntax near '2022'.", Can someone please help with what I am doing wrong?
Thanks in advance.
#TABLE OUTPUT
DECLARE #col NVARCHAR(MAX);
DECLARE #sql NVARCHAR(MAX);
SET #col =
(
SELECT STRING_AGG(t.[WeekEnd], ',')
FROM
(SELECT DISTINCT [WeekEnd] FROM #TABLE) AS t
);
SET #sql
= 'Select *, ' + #col+ '
from
(select #TABLE.PTLITNBR,#TABLE.PTLWHSE,#TABLE.PTLDATATYPE,#TABLE.WeekEnd,#TABLE.Orders from #TABLE) as t
PIVOT
(MAX(Orders) for WeekEnd in (' + #col + N')) as Pivot_Table';
EXECUTE (#sql);
DECLARE #cols AS NVARCHAR(MAX)
, #query AS NVARCHAR(MAX);
SET #cols =
(
SELECT string_agg(CONVERT(NVARCHAR(MAX), QUOTENAME(TempTb.WeekEnd)), ', ')
FROM
(SELECT DISTINCT WeekEnd FROM #temp1) TempTb --distinct weekend dates selected as there a
);
SET #query
= N'SELECT p.PTLWHSE, p.PTLITNBR, p.PTLDATATYPE, ' + #cols
+ N' from
(
select PTLWHSE,PTLITNBR,PTLDATATYPE,WeekEnd, Orders
from #temp1 AS TempTb
) x
pivot
(
max(Orders)
for WeekEnd in (' + #cols + N')
) p ';
EXEC sp_executesql #query;

Pivot join with two columns having varchar datatype in SQL Server 2012

I need to use pivot to create time table from the following data:
I'm using this query
select
start_time, end_time, s.subj_name, tt.dd
from
time_table tt
inner join
subj s on tt.subjid = s.subjid
I am able to pivot my result to
I used following SQL code to do that:
--Declare necessary variables
DECLARE #SQLQuery AS NVARCHAR(MAX)
DECLARE #PivotColumns AS NVARCHAR(MAX)
--Get unique values of pivot column
SELECT #PivotColumns = COALESCE(#PivotColumns + ',','') + QUOTENAME(dd)
FROM (SELECT DISTINCT(dd)
FROM time_table tt
WHERE divid = 1 AND tt.active = 1) AS PivotExample
SELECT #PivotColumns
--Create the dynamic query with all the values for
--pivot column at runtime
SET #SQLQuery =
N'SELECT start_time,end_time, ' + #PivotColumns + '
FROM [dbo].[time_table]
PIVOT( SUM(subjid)
FOR dd IN (' + #PivotColumns + ')) AS P'
SELECT #SQLQuery
--Execute dynamic query
EXEC sp_executesql #SQLQuery
Do help me out to get subjectname as value instead of subjectid
Since you are pivoting a VARCHAR, you can't use SUM, but have to use MAX or MIN
Try instead:
SET #SQLQuery =
N'SELECT start_time,end_time, ' + #PivotColumns + '
FROM [dbo].[time_table]
PIVOT( MAX(subjectname)
FOR dd IN (' + #PivotColumns + ')) AS P'
Found answer for it which provides simpler way to get it.
click to get answer

is any other way to do in dynamic pivot

while answering one question i got struck with other question in mind.when it is normal pivot it is working fine but if i'm trying to do Dynamic query when the problem arises
after answering he asked for Dynamic Pivot
PIVOT the date column in SQL Server 2012
if OBJECT_ID('tempdb..#temp') is not null
begin
drop table #temp
end
CREATE table #temp (dated varchar(10),E1 int,E2 int,E3 int,E4 int)
insert into #temp
(dated,E1,E2,E3,E4)values
('05-27-15',1,1,2,3),
('05-28-15',2,3,NULL,5),
('05-29-15',3,4,null,2)
DECLARE #statement NVARCHAR(max)
,#columns NVARCHAR(max)
SELECT #columns = ISNULL(#columns + ', ', '') + N'[' + tbl.dated + ']'
FROM (
SELECT DISTINCT dated
FROM #temp
) AS tbl
SELECT #statement = 'Select P.col,MAX('+#columns+') from (
select col,' + #columns + ' from (
select * from #temp
CROSS APPLY(values(''E1'',E1),(''E2'',E2),(''E3'',E3),(''E4'',E4))cs (col,val))PP
PIVOT(MAX(val) for dated IN (' + #columns + ')) as PVT)P
GROUP BY P.COL
'
PRINT #statement
EXEC sp_executesql #statement = #statement
my problem is how can i take MAX() conditions for the all dates dynamically like
max(05-27-15),max(05-28-15) etc dates are coming dynamically how to assign max condition
Moving the MAX aggregate to column list variable will fix the issue
DECLARE #statement NVARCHAR(max),
#columns NVARCHAR(max),
#select_columns NVARCHAR(max)
SELECT #select_columns = Isnull(#select_columns + ', ', '')+ N'MAX([' + tbl.dated + '])'
FROM (SELECT DISTINCT dated
FROM #temp) AS tbl
SELECT #columns = Isnull(#columns + ', ', '') + N'[' + tbl.dated+ ']'
FROM (SELECT DISTINCT dated
FROM #temp) AS tbl
SELECT #statement = 'Select P.col,' + #select_columns
+ ' from (
select col,' + #columns
+ ' from (
select * from #temp
CROSS APPLY(values(''E1'',E1),(''E2'',E2),(''E3'',E3),(''E4'',E4))cs (col,val))PP
PIVOT(MAX(val) for dated IN (' + #columns
+ ')) as PVT)P
GROUP BY P.COL
'
PRINT #statement
EXEC sp_executesql #statement = #statement

Dynamic pivoting SQL Server 2012

I am making attempts to run my first dynamic pivot in SQL Server 2012.
My #temp table that I am using for the dynamic pivoting looks like this.
YearMonth Agreement nr Discount
------------------------------------
201303 123 1
201303 12 0
201304 1 0
I am running this code and it does not work:
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName = ISNULL(#ColumnName + ',', '') + QUOTENAME(YearMonth )
FROM (SELECT DISTINCT YearMonth FROM #FINAL) AS Courses
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT [Agreement nr],YearMonth , ' + #ColumnName + '
FROM #FINAL
PIVOT(
COUNT(agreement nr)
FOR YearMonth IN (' + #ColumnName + ') AS PVTTable'
--Execute the Dynamic Pivot Query
EXECUTE #DynamicPivotQuery;
The error message I am getting is
FOR YearMonth IN ([201403]) AS PVTTable' is not a valid identifier.
What am I missing here?
The cause of the error is that you're missing a parenthesis before you alias the Pivot. More than this however your pivot was rather inefficient.
You should select what you need for the source table in your pivot otherwise it could run for a long time and produce a lot of rows with null returns.
The below is fixed and hopefully more efficient:
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(YearMonth )
FROM (SELECT DISTINCT YearMonth FROM #FINAL) AS Courses
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT ' + #ColumnName + '
FROM (Select [Agreement nr], YearMonth from #FINAL) src
PIVOT(
COUNT([Agreement nr])
FOR YearMonth IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXECUTE sp_executesql #DynamicPivotQuery;
You forgot to close pivot.
PIVOT(
COUNT(Kundavtalid)
FOR YearMonth IN (' + #ColumnName + ')
) AS PVTTable' -- here you miss pathernesis
You are missing a parenthesis
SET #DynamicPivotQuery =
N'SELECT [Agreement nr],YearMonth , ' + #ColumnName + '
FROM #FINAL
PIVOT(
COUNT([agreement nr])
FOR YearMonth IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query

How to declare dynamic parameter from stored procedure into code behind

I have one stored procedure. The parameter in the stored procedure is dynamic.
I don't know to declare and use the parameter in code behind(VB.net) of my page.
This is the stored procedure:
CREATE PROCEDURE [dbo].[Gdata2]
--#employeeID varchar(10),
--#employeeCostCenterCode varchar(20)
AS
BEGIN
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','') + QUOTENAME(Product)
FROM (SELECT DISTINCT Product FROM V_SBR_Product) AS Products
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery = N'SELECT Quarter, ' + #ColumnName +
'FROM V_SBR_Product ' +
'PIVOT(COUNT(Total) FOR Product IN (' + #ColumnName +
')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
END