! sql. . , entity_table_id , entity_object_id __ + 'id', property_value property_code .
if object_id('tempdb..
drop table
create table
insert into
(1,'person'),
(2,'site')
if object_id('tempdb..#property') is not null
drop table
create table
insert into
(1,'PERSON_FIRST_NAME'),
(2,'PERSON_LAST_NAME'),
(3,'PERSON_BIRTH_DATE'),
(4,'SITE_NAME'),
(5,'SITE_PHONE_NR_1'),
(6,'SITE_PHONE_NR_2'),
(7,'SITE_LATITUDE'),
(8,'SITE_LONGITUDE'),
(9,'SITE_CITY'),
(10,'SITE_COUNTRY'),
(11,'SITE_ZIP_CODE')
if object_id('tempdb..#property_value_varchar') is not null
drop table
create table
insert into
(1,1,1,1,'Richard'),
(2,2,1,1,'Hammer'),
(3,1,1,2,'Bruce'),
(4,2,1,2,'Heaton'),
(5,4,2,1,'BatCave'),
(6,5,2,1,'+49123456789'),
(7,4,2,2,'BigCompany'),
(8,5,2,2,'987654321'),
(9,6,2,2,'147852369'),
(10,9,2,2,'Berlin'),
(11,10,2,2,'Germany'),
(12,11,2,2,'14167')
if object_id('tempdb..#property_value_datetime') is not null
drop table
create table
insert into
(1,3,1,1,'1985-05-31')
if object_id('tempdb..#property_value_number') is not null
drop table
create table
insert into
(1,7,2,1,1.402636),
(2,8,2,1,7.273922)
declare @tableid int,@sql varchar(max)
set @tableid = 1
select @sql = 'select entity_object_id ' + entity_table_name + 'id,
#ColumnListCast#
from (
select
e.entity_table_name,
pv.entity_object_id,
pv.property_value,
p.property_code
from #entity_tables e
inner join (
select entity_table_id,entity_object_id,property_id,property_value from #property_value_varchar union all
select entity_table_id,entity_object_id,property_id,cast(property_value as varchar(255)) from #property_value_datetime union all
select entity_table_id,entity_object_id,property_id,cast(property_value as varchar(255)) from #property_value_number
) pv
on pv.entity_table_id = e.entity_table_id
inner join #property p
on p.property_id = pv.property_id
where e.entity_table_id = ' + cast(@tableid as varchar(5)) + '
) p
pivot (
max(property_value)
for property_code in (
#ColumnList#
)
) piv' from
declare @ColumnList varchar(max),
@ColumnListCast nvarchar(max)
set @ColumnList = ''
set @ColumnListCast = ''
select @ColumnList = @ColumnList + '[' + p.property_code + ']' + case row_number() over(order by p.property_id desc) when 1 then '' else ',' end,
@ColumnListCast = @ColumnListCast + 'cast([' + p.property_code + '] as ' + t.CastValue + ') [' + p.property_code + ']' + case row_number() over(order by p.property_id desc) when 1 then '' else ',' end
from
inner join (
select property_id,'varchar(255)' CastValue from
select property_id,'datetime' CastValue from
select property_id,'float' CastValue from
) t
on t.property_id = p.property_id
order by p.property_id
set @sql = replace(replace(@sql,'#ColumnList#',@ColumnList),'#ColumnListCast#',@ColumnListCast)
exec(@sql)