Share via

dynamic query

Hemant Karnik 121 Reputation points
2021-01-29T16:02:16.98+00:00

hi
I am trying below query
the problem is when i execute the result of @Query without pivot clause I get the values of Balance4
however when I try to use Pivot Clause I get Null for Sum(Balance4)

what wrong I am doing ... Please help

DECLARE @Query Nvarchar(max)

DECLARE @pivotcolumns NVARCHAR(MAX)
declare @asondate datetime ='20180117'
select @pivotcolumns=coalesce(@pivotcolumns + ',',' ')+QUOTENAME(rtrim(Name)) from pbranches
set @Query = N' select PrdAcctId,PrdCd, ' + @pivotcolumns + '
into ##tempdb
FROM
(
select * from
( select c.Name,cast(a.LBrCode as varchar(5)) branch,a.PrdAcctId,substring(a.PrdAcctId,1,8) prd, b.PrdCd,Balance4 ,
rank () over (partition by a.LBrCode,a.PrdAcctId order by CblDate desc) rnk
from
cl_balances a inner join pmaster b on a.LBrCode=b.LBrCode and rtrim(substring(a.PrdAcctId,1,8))=rtrim(b.PrdCd)
inner join D001003 c on a.LBrCode=c.PBrCode
where convert(char(8),a.CblDate,112)<='+ convert(char(8),@asondate,112)+' and floor(substring(a.PrdAcctId,17,8))=0
)x where rnk=1
) SAVI
pivot
( sum(Balance4) for branch in (' + @pivotcolumns + ')) m'
select @Query mq
exec sp_executesql @Query

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.


Answer accepted by question author

Erland Sommarskog 134.7K Reputation points MVP Volunteer Moderator
2021-01-29T22:56:08.167+00:00

Before you start to build dynamic queries, write a static query with fixed columns so you get the syntax right. Then you can start to write dynamic queries.

I have some tips on crafting dynamic pivots here: http://www.sommarskog.se/dynamic_sql.html#pivot. You will find that I don't use the PIVOT operator...

Was this answer helpful?


1 additional answer

Sort by: Most helpful
  1. EchoLiu-MSFT 14,626 Reputation points
    2021-02-04T07:24:09.447+00:00

    Glad your problem is solved.
    If you have any question, please feel free to let me know.

    Regards
    Echo

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.