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.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 How to trim characters when joining two table?

Author  Topic 

naamaz
Starting Member

1 Post

Posted - 2012-05-09 : 11:42:19
I need to trim the 4 last characters from a field in order to join 2 tables.
for example: I need 000.111.222.333 to turn to 000.111.222 since in one table appears the long version and in the second - the short one. Thus there's no way for me to join the 2 tables without "trimming" the '.333' segment.
(note that "TRIM" won't help here since it cuts only spaces and not characters)

I know that's a tricky one so - respect to whoever succeed in solving, along with my endless gratitude

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-05-09 : 12:09:37
You can join the two tables using a like clause or by trimming the last four characters like this:

-- Trimming

Table1 t1
INNER JOIN Table2 t2 ON LEFT(t1.Col1,LEN(t1.Col1)-4) = t2.Col2

-- Like clause
Table1 t1
INNER JOIN Table2 t2 ON t1.Col1 LIKE t2.Col2+'%'
t1.Col1 is the one that is like 000.111.222.333 and t2.Col2 is the shorter one that is like 000.111.222
Go to Top of Page
   

- Advertisement -