Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
MattieMich7
Starting Member
2 Posts |
Posted - 2009-04-09 : 21:14:12
|
| Table1-------------- LocID LangID100 1100 2200 1Table2--------------LangID Desc1 English2 SpanishAs part of a report I'm creating, I need to list out the languages by location. So based on the tables above, I want to write a query that will result in the following:LocID Languages100 English, Spanish200 EnglishAny help would be much appreciated. |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-04-10 : 06:12:19
|
| [code];With CTE(LocID,Language)AS(SELECT t1.LocID,t2.Desc AS LanguageFROM Table1 t1JOIN Table2 t2ON t2.LangID=t1.LangID)SELECT DISTINCT LocID,STUFF((SELECT ',' + Language FROM CTE WHERE LocID=c.LocID FOR XML PATH('')),1,1,'')FROM CTE c[/code] |
 |
|
|
pmohans123
Starting Member
5 Posts |
Posted - 2009-04-10 : 06:42:56
|
| Hi,Please try with this example, please replace temp table (#temp1 and #temp2) to your real table.Create table #temp1 (locid int, [langid] int)Create table #temp2 ([langid] int, [Desc] varchar(50))Insert into #temp1 values (100, 1)Insert into #temp1 values (100, 2)Insert into #temp1 values (200, 1)Insert into #temp2 values (1, 'English')Insert into #temp2 values (2, 'Spanish')Select * from #temp1Select * from #temp2Create Table #temp3(id int identity(1,1), locid int, Descripton varchar(500))Insert into #temp3 (locid)Select distinct locid from #temp1Declare @var varchar(100), @Cnt int, @Totcnt int, @Locid intSet @Cnt = 1Select @Totcnt = count(*) from #temp3While @cnt <= @TotcntBeginSet @var = Null Select @locid = locid from #temp3 where id = @cntSelect @var = Isnull(@var + ',','') + [desc] from #temp1 a inner join #temp2 b on a.[langid]=b.[langid] where locid = @locidUpdate #temp3 set Descripton = @var where locid = @locidSet @cnt = @cnt + 1EndSelect locid, Descripton from #temp3Drop table #temp1Drop table #temp2Drop table #temp3I don’t know whether it is a feasible solution or not, but you will get the correct answer.Thanks,Mohan |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-04-10 : 06:53:48
|
| why use loop? always try to go for set based solution. thats faster. |
 |
|
|
MattieMich7
Starting Member
2 Posts |
Posted - 2009-04-10 : 09:25:51
|
| Thank you visakh16, that worked perfectly.I'm a SQL newbie, so I am not at all familiar with the STUFF function you used. Is there a good place to find more info on that or could you elaborate on what your approach was?Thanks again! |
 |
|
|
|
|
|
|
|