Author |
Topic |
satheesh
Posting Yak Master
152 Posts |
Posted - 2014-03-11 : 07:13:47
|
Hi All,I have 'codes' and 'Description' field in 'ecode' table and 'codes' in quote table values for 'Codes' in quote table is like Quoteid Codes0012 LB,WS0031 WDC----In 'ecode' table 'description' column contain the description for each codefor eg :Ecode Table : -Codes DescriptionLb - Late BookingWS - Winter SportsWDC - Wedding Cover----How to select 'description' when retrieving data from quote tableie. i need Output0012 Latebooking,Winter Sports0031 Wedding CoverAny help will be highly appreciated.ThanksSG |
|
James K
Master Smack Fu Yak Hacker
3873 Posts |
Posted - 2014-03-11 : 08:26:40
|
If you have a choice, don't store the data this way as comma-separated strings. This is not a normalized table and so very difficult to work with. If this is all you have, one way to accomplish what you want to do would be use a string splitter function. Copy and install the string splitter function from this page. http://www.sqlservercentral.com/articles/Tally+Table/72993/ Then use it like in the example below:CREATE TABLE #Codes(QuoteId VARCHAR(4),Codes VARCHAR(32));INSERT INTO #Codes VALUES ('0012','LB,WS'),('0031','WDC');CREATE TABLE #ECode (Codes VARCHAR(4), [Description] VARCHAR(32));INSERT INTO #ECode VALUES ('Lb','Late booking'),('WS','Winter sports'),('WDC','Wedding Cover');;WITH cte AS ( SELECT c.QuoteId,e.*,s.ItemNumber FROM #Codes c CROSS APPLY dbo.DelimitedSplit8k(Codes,',') s INNER JOIN #ECode e ON e.codes = s.Item)SELECT a.QuoteId, STUFF(b.[Descriptions],1,1,'') AS [Descriptions]FROM (SELECT DISTINCT QuoteId FROM cte) a CROSS APPLY ( SELECT ',' + [Description] FROM cte b WHERE a.QuoteId = b.QuoteId ORDER BY b.ItemNumber FOR XML PATH('') )b([descriptions]);DROP TABLE #Codes;DROP TABLE #ECode; |
 |
|
VeeranjaneyuluAnnapureddy
Posting Yak Master
169 Posts |
Posted - 2014-03-11 : 09:09:44
|
DECLARE @Code TABLE(Quoteid INT,Codes VARCHAR(20))INSERT INTO @Code VALUES(0012,'LB,WS'),(0031,'WDC')DECLARE @Des TABLE(QuoteId INT,Codes VARCHAR(10),Description VARCHAR(30))INSERT INTO @Des VALUES(0012,'Lb','Late Booking'),(0012,'WS','Winter Sports'),(0031,'WDC','Wedding Cover');WITH TempAS(SELECT u.quoteid,u.codes,p.DescriptionFROM @code uINNER JOIN @des pON ',' + u.Codes + ',' LIKE '%,' + CAST(p.Codes AS varchar(15)) + '%')SELECT DISTINCT quoteid,STUFF((SELECT ',' + Description FROM Temp WHERE Quoteid = t.QuoteId ORDER BY Quoteid FOR XML PATH('')),1,1,'') AS PublicationNamesFROM (SELECT DISTINCT Quoteid,Description FROM Temp) tVeera |
 |
|
|
|
|