A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
Hi @ravibabu ,
Please refer updated query from below:
declare @sql nvarchar(max)
declare @s nvarchar(max)
declare @s1 nvarchar(max)
SELECT @s = STUFF((
SELECT distinct ',[' + trim(addresscode)+']'
FROM emp_addressline
FOR XML PATH('')
), 1, 1, '')
FROM emp_addressline
SELECT @s1 = STUFF((
SELECT distinct ',trim([' + trim(addresscode)+']) ['+trim(addresscode)+']'
FROM emp_addressline
FOR XML PATH('')
), 1, 1, '')
FROM emp_addressline
set @sql= N'
select a.empid, city, doj,
(
select
trim(city) city,
trim(state) state,
trim(country) country,
(
select '+@s1+'
from emp_addressline
pivot
(
max(addressline) for addresscode in ('+@s+')
)
as p
where empid = a.empid
for json path
) as addreslineinfo,
trim(p.prooftype) prooftype
for json path
) as empjson
from emp_addr a
left join emp_proof p on p.empid = a.empid'
EXECUTE sp_executesql @sql
Output:
empid city doj empjson
1 bang 2018-08-03 [{"city":"bang","state":"KA","country":"Ind","addreslineinfo":[{"district":"street2","street1":"street1","taluka":"street2"}],"prooftype":"aadhar"}]
2 chen 2018-02-04 [{"city":"chen","state":"Tn","country":"Ind","addreslineinfo":[{"3":"street4","district":"street3","street1":"street1"}],"prooftype":"voterid"}]
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.