TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Tarun Kumar
NA
26
470
Dynamic Pivot in SQL Server
Mar 9 2018 12:42 AM
I have few hundred thousand records to pivot dynamically. I've tried the following query and it works fine for a selected emploeeid.
declare
@cols nvarchar(
max
)=N
''
,@sql nvarchar(
max
)=N
''
,@uniqcols nvarchar(
max
)=N
''
select
@cols=
isnull
(@cols+
','
,
''
)+QUOTENAME(concat(format(FromDate,
'Y'
),
' to '
,format(ToDate,
'Y'
)))
from
salaries
where
EmpId=15001
print @cols
set
@sql=
'select Firstname '
+@cols+'
from
(
select
e.Empid,e.Firstname,concat(format(s.FromDate,
''
Y
''
),
''
to
''
,format(s.ToDate,
''
Y
''
))
as
period,s.salary
from
employees e
join
salaries s
on
e.EmpId=s.Empid
where
e.EmpId=15001
)
as
source
pivot
(
sum
(salary)
for
period
in
(
'+stuff(@cols,1,1,'
')+'
)
)
as
derived'
print @sql
exec
sp_executesql @sql
and when i want to pivot all the records of the employees, it is executing a very long time. Is it the right way to do or any better way to do? I have stopped the execution after half-an-hour as i didn't get an result.
declare
@cols nvarchar(
max
)=N
''
,@sql nvarchar(
max
)=N
''
,@uniqcols nvarchar(
max
)=N
''
select
@cols=
isnull
(@cols+
','
,
''
)+QUOTENAME(concat(format(FromDate,
'Y'
),
' to '
,format(ToDate,
'Y'
)))
from
salaries
print @cols
set
@sql=
'select Firstname '
+@cols+'
from
(
select
e.Empid,e.Firstname,concat(format(s.FromDate,
''
Y
''
),
''
to
''
,format(s.ToDate,
''
Y
''
))
as
period,s.salary
from
employees e
join
salaries s
on
e.EmpId=s.Empid
)
as
source
pivot
(
sum
(salary)
for
period
in
(
'+stuff(@cols,1,1,'
')+'
)
)
as
derived'
print @sql
exec
sp_executesql @sql
thanks in advance
Reply
Answers (
1
)
Sql server-concepts
Inserting Lakhs of Records At a time