sql - How to make dynamic pivot for this table when I pass only one parameter @did int? -
i have 2 tables, @details
, @contactdetails
. in 2 tables, @details
static table in contactid
primary key, , foreign key @contactdetails
here tables data:
declare @details table (contactid int identity(1,1), value varchar(200)) insert @details select 'phonenumber' union select 'mobilenumber' union select 'address1' union select 'address2' union select 'employeename' union select 'employeeid' declare @contactdetails table (detailid int identity(1,1), did int, contactid int, detailsvalue varchar(200) ) insert @contactdetails select 1,5,'siva' union select 1,6,'sia001' union select 1,2,'9344139991' union select 2,1,'245678' union select 2,2,'1686597' union select 2,5,'ganesh' union select 1,3,'st-road' select * @details
the output is:
contactid value ---------------------- 1 phonenumber 2 mobilenumber 3 address1 4 address2 5 employeename 6 employeeid select * @contactdetails
the output second query is:
detailid did contactid detailsvalue ----------------------------------- 1 1 6 siva 2 1 5 sia001 3 1 2 9344139991 4 2 1 245678 5 2 2 1686597 6 2 5 ganesh 7 1 3 st-road
in @contactdetails
column have value of did
column used show 1 particular employee detail in stored procedure using
parameter @did int
- tried query
declare @did int=1 select (select value @details contactid=a.contactid)as contactid, a.detailsvalue @contactdetails a.did=@did
which show result this
contactid detailsvalue employeeid siva employeename sia001 mobilenumber 9344139991 address1 st-road
and trying output this
employeeid employeename mobilenumber address1 sia001 siva 9344139991 st-road
can 1 plz me
the basic set if know value ahead of time be:
select * ( select c.did, d.value, c.detailsvalue details d inner join contactdetails c on d.contactid = c.contactid ) src pivot ( max(detailsvalue) value in (employeeid, employeename, address1, mobilenumber, phonenumber) ) piv;
see sql fiddle demo
the above gets of values if want implement dynamic sql filter result based on @did
, use:
declare @cols nvarchar(max), @query nvarchar(max), @did int set @did = 1 select @cols = stuff((select ',' + quotename(d.value) details d inner join contactdetails c on d.contactid = c.contactid c.did = @did group d.value, c.detailid order c.detailid xml path(''), type ).value('.', 'nvarchar(max)') ,1,1,'') set @query = 'select ' + @cols + ' ( select d.value, c.detailsvalue details d inner join contactdetails c on d.contactid = c.contactid c.did = '+cast(@did varchar(10))+' ) x pivot ( max(detailsvalue) value in (' + @cols + ') ) p ' execute(@query);
see sql fiddle demo
Comments
Post a Comment