日期:2014-05-17  浏览次数:20464 次

请教字符串比较问题
有两组字符串 第一组 第二组 比较出结果
  LGALGDLGU LGALGDLGU 一样的字符串
  LGALGDLGU LGALGULGD 一样的字符串
  LGALGDLGU LGDLGALGU 一样的字符串
  LGALGDLGU LGDLGULGA 一样的字符串
  LGALGDLGU LGULAGLGD 一样的字符串
  LGALGDLGU LGULGDLGA 一样的字符串
有没有SQL语句,能否判断出上面二组字符串是一样的字符串。规律见上。知道的告诉我下,谢谢



------解决方案--------------------
SQL code
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([col1] varchar(9),[col2] varchar(9))
insert [tb]
select 'LGALGDLGU','LGALGDLGU' union all
select 'LGALGDLGU','LGALGULGD' union all
select 'LGALGDLGU','LGDLGALGU' union all
select 'LGALGDLGU','LGDLGULGA' union all
select 'LGALGDLGU','LGULAGLGD' union all
select 'LGALGDLGU','LGULGDLGA'
go

create function str_def(@s1 varchar(100),@s2 varchar(100))
returns int
as
begin
  declare @result int
  declare @t1 table(col char(1))
  declare @t2 table(col char(1))
  insert @t1
  select substring(@s1,number,1)
  from master..spt_values
  where type='P' and number between 1 and len(@s1)
  insert @t2
  select substring(@s2,number,1) 
  from master..spt_values
  where type='P' and number between 1 and len(@s2)
  if not exists
  (
    select 1 
    from (select col,count(1) as cnt from @t1 group by col) a 
    where not exists
    (
      select 1 
      from (select col,count(1) as cnt from @t2 group by col) b 
      where a.col=b.col and a.cnt=b.cnt
    )
  )
    set @result=1
  else
    set @result=0
  return @result
end
go

select *,dbo.str_def(col1,col2) AS RESULT  from tb

--测试结果:
/*
col1      col2      RESULT
--------- --------- -----------
LGALGDLGU LGALGDLGU 1
LGALGDLGU LGALGULGD 1
LGALGDLGU LGDLGALGU 1
LGALGDLGU LGDLGULGA 1
LGALGDLGU LGULAGLGD 1
LGALGDLGU LGULGDLGA 1

(6 行受影响)

*/

drop function str_def