select * from tabTest
WHERE LikeNum(c1+c2+c3+c4+c5,'B')=2其中likenum為自定義函數。

解决方案 »

  1.   

    select * from tabletest
    where case c1 when 'B' then 1 else 0 end
    +case c2 when 'B' then 1 else 0 end
    +case c3 when 'B' then 1 else 0 end
    +case c4 when 'B' then 1 else 0 end
    +case c5 when 'B' then 1 else 0 end
    =2
      

  2.   

    --测试--测试数据
    create table tabletest(id int,c1 char(1),c2 char(1),c3 char(1),c4 char(1),c5 char(1))
    insert tabletest
    select 1,'A','B','A','B','C'
    union all select 2,'B','B','B','A','C'
    union all select 3,'B','C','C','B','A'
    union all select 4,'C','A','A','B','B'
    union all select 5,'A','C','A','B','C'
    go--查询
    select * from tabletest
    where case c1 when 'B' then 1 else 0 end
    +case c2 when 'B' then 1 else 0 end
    +case c3 when 'B' then 1 else 0 end
    +case c4 when 'B' then 1 else 0 end
    +case c5 when 'B' then 1 else 0 end
    =2
    go--删除测试
    drop table tabletest/*--测试结果
    id          c1   c2   c3   c4   c5   
    ----------- ---- ---- ---- ---- ---- 
    1           A    B    A    B    C
    3           B    C    C    B    A
    4           C    A    A    B    B(所影响的行数为 3 行)
    --*/
      

  3.   

    select * 
    from tabTest
    where (case when c1='B' then 1 else 0 end 
    +when c2='B' then 1 else 0 end 
    +when c3='B' then 1 else 0 end 
    +when c4='B' then 1 else 0 end 
    +when c5='B' then 1 else 0 end )=2
      

  4.   

    --統計字符串@vchChildString在字符串@vchMainString中出現的次數
    -- DROP FUNCTION  dbo.likenum
    CREATE FUNCTION dbo.likenum(@vchMainString varchar(1000),@vchChildString varchar(100))
    RETURNS int
    AS
    BEGIN
    DECLARE @intCount int
    DECLARE @intStart int
    DECLARE @intChildLength int
    SET @intCount=0
    SET @intStart=1
    SET @intChildLength=ISNULL(LEN(@vchChildString),0) WHILE( CHARINDEX(@vchChildString,@vchMainString,@intStart)>0)
    BEGIN
    SET @intStart= CHARINDEX(@vchChildString,@vchMainString,@intStart)+@intChildLength
    SET @intCount=@intCount+1
    END RETURN(@intCount)END
      

  5.   

    select *
    from tabTest
    where len(isnull(c1,'') + isnull(c2,'') + isnull(c3,'') + isnull(c4,'') + isnull(c5,'')) - len(replace(isnull(c1,'') + isnull(c2,'') + isnull(c3,'') + isnull(c4,'') + isnull(c5,''),'b',''))=2