sql - How to concatenate Multiple Rows from Multiple Tables Efficiently -


i have multiple tables foreign key main table. tables this:

sisters

mainid    idno   .... 111111       1   ....           111111       1   ....           111111       1   .... 222222       1   ....           111111       2   ....           

brothers

mainid    idno   .... 111111     555   ....           111111     333   ....           111111     111   .... 222222     222   ....           111111     321   ....           

uncles

mainid    idno   .... 111111     561   ....           111111     121   ....           111111     331   .... 222222     451   ....           111111     672   ....  

i need concatenate idnos in can't seem example maybe can't 672

select      ',' + s1.idno + ',' + b1.idno + ',' + u1.idno [text()]       sisters s1, brothers b1, uncles u1, maintable       d1.mainid = maintable.id      , s1.mainid = maintable.id      , b1.mainid = maintable.id  xml path('') 

i tried seperate tables , concanate later getting slower way. can do?

expected output:

,1,1,1,1,2,555,333,111,222,321,561,121,331,451,672 

based on expected output appears mainid column in each of 3 tables has no in output (if so) should work though iam not sure scale handle 600k+ records. out of curiosity why want concatenate such large list of values ?

declare @x varchar(max) = ''  select @x = @x + ',' + cast(a.idno varchar)  ( select 1 idno union select 2 idno union select 3 idno union select 4 idno  ) -- pretend sisters tables xml path('') print @x -- debugging purposes  select @x = @x + ',' + cast(b.id varchar)  ( select 55 idno union select 66 idno union select 77 idno union select 88 idno  ) b -- pretend brothers tables  print @x -- debugging purposes  select @x = @x + ',' + cast(c.idno varchar)  ( select 555 idno union select 666 idno union select 777 idno union select 888 idno  ) c -- pretend uncles tables   print @x -- final output  select @x xml_output xml path('')  

output:

,1,2,3,4 ,1,2,3,4,55,66,77,88  ,1,2,3,4,55,66,77,88,555,666,777,888 -- final result  <xml>,1,2,3,4,55,66,77,88,555,666,777,888</xml> -- xml output 

so in case (again not sure how behave on large tables):

declare @x varchar(max) = '' select  @x = @x + ',' + cast(a.idno varchar)  ( select mainid ,   idno sisters  union select mainid ,   idno brothers union select mainid ,   idno uncles )   select @x xml_output xml path('')  

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -