-1

次のようなテーブルを想像してください。

ID - NAME
1    BART
2    LISA
3    HOMER
4    MISA
5    HOMRE

そして、3文字以上の文字が等しい行のみを選択したいと思います。したがって、この選択の後、次を取得する必要があります。

ID - NAME
2    LISA
3    HOMER
4    MISA
5    HOMRE

SQL Server 2008 でそれを行う方法は?

4

2 に答える 2

0

任意の位置で一般的な文字をテストするには、SQL 関数を使用できます。

create function dbo.CommonChars(@str1 varchar(255), @str2 varchar(255))
returns int
begin
    declare @count int
    declare @cur int
    set @cur = 1
    set @count = 0
    while @cur <= LEN(@str1)
    begin
        if charindex(substring(@str1, @cur, 1), @str2) > 0
        begin
            set @count = @count + 1
        end
        set @cur = @cur + 1
    end
    return @count
end

テストデータ:

create table #test (
  id int,
  name varchar(255)
);

insert into #test 
select 1, 'BART' union all
select 2, 'LISA' union all
select 3, 'HOMER' union all
select 4, 'MISA' union all
select 5, 'HOMRE'

テストステートメント:

select * from #test t1 where exists
    (select 1 from #test t2
        where t1.id != t2.id and
        dbo.CommonChars(t1.name, t2.name) >= 3)

戻り値:

id  name
2   LISA
3   HOMER
4   MISA
5   HOMRE

Note: If one of the strings has multiple occurences of one character, the function will not work as expected (e.g. if you have the strings "MUMMY" and "MA", "MUMMY" will be returned by above query; it has 3 Ms "in common" with "MA", since the function checks separately for each M if it is contained in any of the other strings). You'd have to e.g. delete the matched characters from the second string to prevent such behavior; I'll leave that as an exercise for the interested reader.

于 2012-08-21T08:33:52.580 に答える