drop table if exists [#_exportTable#]; with base as ( select skuId, sku, skuDesc, cast( json_value( purchasingData, '$.operatorId' ) as int ) as operatorId from [#_voidMatrixTable#] with (nolock) where cast( json_value( purchasingData, '$.selected' ) as bit ) = 1 ) select b.skuId, b.sku, b.skuDesc, opr.operatorId, opr.companyName, opr.territoryName, concat_ws( ' ', opr.salesRepFirstName, opr.salesRepLastName ) salesRepFulName into [#_exportTable#] from base b inner join tbl_DW_CRMOperators_MFR207 opr on opr.operatorId = b.operatorId order by sku, companyName; alter table [#_exportTable#] add constraint [pk_#_exportTable#] primary key ( sku, companyName, skuId, operatorId ); select count(*) as rowsExported from [#_exportTable#] with (nolock) insert into tbl_RPT_Exports ( ownerType, ownerId, status, statusEx, sourceSQL, linkType, linkId, createTime, statusTime, fileName, fileFormat, utcTimestamp ) values ( , , '?', 'pending', , '', -1, , , , , ) select status, statusEx from tbl_RPT_ExportStatus where ownerType = and ownerId = and exportId =