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 |
|
jujuju918
Starting Member
3 Posts |
Posted - 2008-10-22 : 18:07:48
|
| Hello,Is there a simple way to select all from a table where a column matches at least 5 specified characters?Thanks,Julius |
|
|
webfred
Master Smack Fu Yak Hacker
8781 Posts |
Posted - 2008-10-22 : 18:14:35
|
| Characters in the given order without a gap?select * from table where column1 like '%webfr%'WebfredNo, you're never too old to Yak'n'Roll if you're too young to die. |
 |
|
|
jujuju918
Starting Member
3 Posts |
Posted - 2008-10-22 : 18:19:41
|
| Well let me rephrased that. I want to compare two colunmn and return only those records that have at least 5 matching character in a row. |
 |
|
|
hanbingl
Aged Yak Warrior
652 Posts |
Posted - 2008-10-22 : 18:56:26
|
| But, You said Specified... that's different than matching two columns on any 5 chars match in a row.If you meant specified. Such as you want to match 'WEBFR' in both Col1 and Col2 thenWHERE COL1 like '%WEBFR%' and COL2 like '%WEBFR%'If you meant to match any 5 characters in a row between the two columns then you'll need some serious logics to go in. Which I am going to work on it in the next hour. |
 |
|
|
jujuju918
Starting Member
3 Posts |
Posted - 2008-10-22 : 19:03:55
|
| Yes you are correct hanbingl. This is exactly what I need. I will await your logic. Thank very much!! |
 |
|
|
hanbingl
Aged Yak Warrior
652 Posts |
Posted - 2008-10-22 : 19:28:43
|
| [code]create function dbo.fn_match5(@col1 varchar(8000), @col2 varchar(8000))returns varchar(8000)asbegindeclare @fivechars varchar(5)declare @startlen int, @len int, @match intset @startlen = 1select @len = len(@col1)-4while @startlen <= @lenbeginselect @fivechars = substring(@col1, @startlen, 5)set @startlen = @startlen + 1if patindex('%'+@fivechars+'%', @col2) > 0beginreturn @fivecharsendendreturn ''end[/code]TEST DATA AND USAGE[code]declare @sample table (id bigint identity(1,1) not null primary key, col1 varchar(10), col2 varchar(10))insert into @sample values('ABCDEFGHIJ','CDEFGABHI')insert into @sample values('ABZDEFGHIJ','ZDEFGABHI')insert into @sample values('ABZDEFGHIJ','ZDEFdABHI')select col1, col2, left(dbo.fn_match5(col1, col2),5) from @samplecol1 col2 ---------- ---------- ----- ABCDEFGHIJ CDEFGABHI CDEFGABZDEFGHIJ ZDEFGABHI ZDEFGABZDEFGHIJ ZDEFdABHI (3 row(s) affected)[/code] |
 |
|
|
|
|
|
|
|