| Author |
Topic |
|
dkloehr
Starting Member
1 Post |
Posted - 2008-09-05 : 21:57:44
|
| My problem is this:In table 1 I have a field which contains a field with a name (ie, John, Ted, Sam) and a text field which contains several numbers, each seperated by a comma and quotes (i.e. '1234', '2345', etc)So the structure of table 1 is something like this:FIELD1 FIELD2John '1234', '2345'Ted '2346', '3456'Sam '3333', '4444'In table 2 I have several records, each containing one number and one city.Table 2 looks like this:FIELD1 FIELD21234 Denver2345 New York2346 Los AngelesI want to know how to link the tables to get the following:FEILD1 FIELD2 FIELD3John 1234 DenverJohn 2345 New YorkTed 2346 Los Angelesetc.Any help is greatly appreciated. Using SQL 2005 on Windows XP.Dennis |
|
|
raky
Aged Yak Warrior
767 Posts |
Posted - 2008-09-06 : 01:43:33
|
| hi try thisdeclare @tab1 table ( field1 varchar(64), field2 varchar(max))insert into @tab1select 'John' ,'1234,2345' union all select 'Ted', '2346,3456' union all select 'Sam', '3333,4444' declare @temp table ( name varchar(64), field varchar(64))insert into @temp SELECT t1.field1, SUBSTRING(t1.field2, v.Number - 1, COALESCE(NULLIF(CHARINDEX(',', t1.field2, v.Number), 0), LEN(t1.field2) + 1) - v.Number + 1) AS field2FROM @tab1 AS t1INNER JOIN master..spt_values AS v ON v.Type = 'p'WHERE SUBSTRING(',_' + t1.field2, v.Number, 1) = ','declare @tab2 table ( field1 varchar(30), field2 varchar(64))insert into @tab2select '1234','Denver' union allselect '2345','New York' union allselect '2346','Los Angeles' select t1.name, t2.field1, t2.field2 from @temp t1left join @tab2 t2 on t2.field1 = t1.field |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-09-06 : 23:32:48
|
| [code]SELECT t1.Name,t1.Number,t2.FIELD2 AS FIELD3FROM (SELECT PARSENAME(REPLACE(FIELD1,' ','.'),1) AS Number,PARSENAME(REPLACE(FIELD1,' ','.'),2) AS NameFROM Table1UNION ALLSELECT FIELD2,PARSENAME(REPLACE(FIELD1,' ','.'),2) AS NameFROM Table1)t1INNER JOIN Table2 t2ON t2.FIELD1=t1.NumberORDER BY t1.Name,t1.Number[/code] |
 |
|
|
|
|
|