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 |
vipulpatel
Starting Member
2 Posts |
Posted - 2014-10-02 : 17:26:31
|
I have a table 1 likeID Region MarketID10 Northwest 120 East 2,330 West 340 North 450 West 1,2Table 2 MarketId Name1 Atlanta2 Seattle3 Chicago4 KansasResult: I am looking for is as below...ID Region MarketID10 Northwest Atlanta20 East Seattle,Chicago30 West Chicago40 North Kansas50 West Atlanta,SeattleBasicall I want to Replace MarketID in Table1 with it's respective names from Table2, How can I do it? Please help.. Thankyou.. |
|
AASC
Starting Member
24 Posts |
Posted - 2014-10-03 : 01:45:05
|
CREATE FUNCTION [dbo].[fnSplit] ( @List VARCHAR(8000), @Delimiter CHAR(1) = ',' )RETURNS @Temp1 TABLE ( ItemId INT IDENTITY(1, 1) NOT NULL PRIMARY KEY, Item VARCHAR(8000) NULL )AS BEGIN DECLARE @item VARCHAR(4000), @iPos INT SET @Delimiter = ISNULL(@Delimiter, ',') SET @List = RTRIM(LTRIM(@List))-- check for final delimiter IF RIGHT(@List, 1) <> @Delimiter -- append final delimiter SELECT @List = @List + @Delimiter-- get position of first element SELECT @iPos = CHARINDEX(@Delimiter, @List, 1) WHILE @iPos > 0 BEGIN-- get item SELECT @item = LTRIM(RTRIM(SUBSTRING(@List, 1, @iPos - 1))) IF @@ERROR <> 0 BREAK-- remove item form list SELECT @List = SUBSTRING(@List, @iPos + 1, LEN(@List) - @iPos + 1) IF @@ERROR <> 0 BREAK-- insert item INSERT @Temp1 VALUES ( @item ) IF @@ERROR <> 0 BREAK-- get position pf next item SELECT @iPos = CHARINDEX(@Delimiter, @List, 1) IF @@ERROR <> 0 BREAK END RETURN ENDGO----------------------------------------------------------------------------------------------------------select ID,Region,MarketID= stuff((SELECT ', ' + nameFROM table1 CROSS APPLY dbo.[fnSplit](table1.MarketId,',') AS bINNER JOIN tabl2 ON tabl2.MarketID=b.itemwhere outertable1.id=table1.idFORXML PATH('') ), 1, 1,'')from table1 outertable1 |
|
|
gbritton
Master Smack Fu Yak Hacker
2780 Posts |
Posted - 2014-10-03 : 09:32:04
|
[code]select t1.id, t1.region, t2.namefrom table1 t1join table2 t2 on t1.marketid = t2.marketid[/code] |
|
|
vipulpatel
Starting Member
2 Posts |
Posted - 2014-10-03 : 14:42:14
|
Thank you so much AASC, it worked and i really appreciate it. Thanks again. Thanks Gbritton as well for reply. |
|
|
|
|
|
|
|