这是我需要作为 SQL 函数的选择查询,通过INTSID
作为参数传递此查询返回一组记录。
DECLARE @colsUnpivot AS NVARCHAR(MAX),
@query As nvarchar(max),
@colsPivot as NVARCHAR(MAX)
select @colsUnpivot = stuff((select ','+ quotename(C.name)
from sys.columns as C
where C.object_id = object_id('tblHRIS_ChildDetails') and
C.name not in ('intCHID', 'intsid')
for xml path('')), 1, 1, '')
select @colsPivot = STUFF((SELECT ','
+ quotename(c.name
+'_'+ cast(t.rn as varchar(10)))
from
(
select row_number() over(partition by intsid order by intCHID) rn
from tblHRIS_ChildDetails
) t
cross apply sys.columns as C
where C.object_id = object_id('tblHRIS_ChildDetails') and
C.name not in ('intCHID', 'intsid')
group by c.name, t.rn
order by t.rn
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'select *
from
(
select col+''_''+cast(rn as varchar(10)) col, value
from
(
select nvrchildname,
cast(nvrchildgender as nvarchar(250)) nvrChildGender,
convert(nvarchar(250), dttchildDOB, 120) dttchildDOB,
cast(nvrnominee as nvarchar(250)) nvrnominee,
nvrchildoccupation,
convert(nvarchar(250), dttCreatedon, 120) dttCreatedon,
convert(nvarchar(250), dttModifiedOn, 120) dttModifiedOn,
convert(nvarchar(250), nvrModifiedby, 120) nvrModifiedby,
row_number() over(partition by intsid order by intCHID) rn
from tblHRIS_ChildDetails
where intsid = 463
) x
unpivot
(
value
for col in ('+ @colsunpivot +')
) u
) x1
pivot
(
max(value)
for col in ('+ @colspivot +')
) p'
exec (@query)