Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
-- When Running below the top 100 percent vs top 100 STRING_AGG is producing different
-- results
if object_id('tempdb..#tabs') is not null drop table #tabs
create table #tabs (drrt nchar(2),drky nchar(10),drdl01 nchar(30),seq bigint)
insert into #tabs
select 'S1','ELEVATION ','Exterior ',3
union
select 'S1','LOT ','Home Site ',1
union
select 'S1','PLAN ','Home Design ',2
union
select 'S1','SUMMARY ','Summary ',99
union
select 'SL','BASEMENT ','Basement ',17
union
select 'SL','BATH ','Bathroom ',16
union
select 'SL','KITCHEN ','Kitchen/Appliances ',15
union
select 'SL','LOOK ','Look ',11
union
select 'SL','OPTIONS ','Options ',18
union
select 'SL','PALETTE ','Palette ',13
--
select string_agg(tabs,',') from (
select top 100 percent tabs='{"ky":"'+ rtrim(drky) + '",' + '"dispval":"' + rtrim(drdl01) +
'",' +'"seq":"' + format(seq,'#########0') +
'"}'
from #tabs order by SEQ) tb
--
select string_agg(tabs,',') from (
select top 100 tabs='{"ky":"'+ rtrim(drky) + '",' + '"dispval":"' + rtrim(drdl01) +
'",' +'"seq":"' + format(seq,'#########0') +
'"}'
from #tabs order by SEQ) tb
Try to order the data:
select string_agg(tabs, ',') within group ( order by seq ) from (
select top 100 percent tabs='{"ky":"'+ rtrim(drky) + '",' + '"dispval":"' + rtrim(drdl01) +
'",' +'"seq":"' + format(seq,'#########0') +
'"}', seq
from #tabs order by SEQ) tb
--
select string_agg(tabs, ',') within group ( order by seq ) from (
select top 100 tabs='{"ky":"'+ rtrim(drky) + '",' + '"dispval":"' + rtrim(drdl01) +
'",' +'"seq":"' + format(seq,'#########0') +
'"}', seq
from #tabs order by SEQ) tb
Note that top 100 is not top 100 percent.