日期:2014-05-18 浏览次数:20822 次
select * from tb where ','+服务用户名+',' like '%,李思,%' 
or
select * from tb where charindex(','+'李思'+',',','+服务用户名+',') > 0
------解决方案--------------------
create table tb(id int,服务用户名 varchar(20))
insert into tb values(1,    '张三,李思') 
insert into tb values(2,    '李思杰,李思') 
insert into tb values(3,    '李思杰,张三')
go
--方法一
select * from tb where ','+服务用户名+',' like '%,李思,%' 
/*
id          服务用户名                
----------- -------------------- 
1           张三,李思
2           李思杰,李思
*/
--方法二
select * from tb where charindex(','+'李思'+',',','+服务用户名+',') > 0
/*
id          服务用户名                
----------- -------------------- 
1           张三,李思
2           李思杰,李思
*/
drop table tb
------解决方案--------------------
agree潇洒老乌龟
------解决方案--------------------
老乌龟就是潇洒,方法不错。
我还有一个办法,楼主为什么不在服务表里把用户名都用{}括起来呢?
就像这样:
id   服务用户名
1    {张三}{李思}
2    {李思杰}{李思}
3    {李思杰}{张三}
然后:
select count(*) from b where 服务用户名 like '%{李思}%'
PS:
我还是推荐采用“潇洒老乌龟”的做法,因为这符合习惯,呵呵。
------解决方案--------------------
因为李思杰也包含了李思,不满足要求,所以两边都加上一个分隔符','
同意老乌龟
------解决方案--------------------
agree潇洒老乌龟
------解决方案--------------------
select count(*) as 记录条数 from b where charindex('李思',服务用户名) > 0
------解决方案--------------------
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
create FUNCTION  [dbo].[Split] (@str_in  VARCHAR(8000),@separator VARCHAR(4) )
	RETURNS @PrimaryIDTable TABLE (ID  VARCHAR(8000))
AS
BEGIN
	DECLARE @Occurrences INT,
		 @Counter INT,
		 @tmpStr VARCHAR(8000)
	
	SET @Counter = 0
	IF SUBSTRING(@str_in,LEN(@str_in),1) <> @separator  
	         SET @str_in = @str_in + @separator
	
	 SET @Occurrences = (DATALENGTH(REPLACE(@str_in,@separator,@separator+'#')) -  DATALENGTH(@str_in))/ DATALENGTH(@separator)
	 SET @tmpStr = @str_in
	
	 WHILE @Counter <= @Occurrences  
	 BEGIN
		  SET @Counter = @Counter + 1
		  INSERT INTO @PrimaryIDTable
		  VALUES ( SUBSTRING(@tmpStr,1,CHARINDEX(@separator,@tmpStr)-1))
		
		  SET @tmpStr = SUBSTRING(@tmpStr,CHARINDEX(@separator,@tmpStr)+1,8000)
		 
		  IF DATALENGTH(@tmpStr) = 0
		  BREAK	 
	 END
	 RETURN
END
select count(*) from b where '李思'in(select 服务用户名 from dbo.Split(b.服务用户名 ,','))
------解决方案--------------------
select * from tb where charindex(','+'李思'+',',','+服务用户名+',') > 0
------解决方案--------------------
select * from tb where charindex(','+'李思'+',',','+服务用户名+',') > 0
------解决方案--------------------