字符串分割 查询有关问题
字符串分割 查询问题
表table1
id Name
1 张三,李四,王五,
2 李四,
3 李四,张三,
需要查询 Name =李四的数据
也就是三条
数据
查询结果格式为:
id Name
1 张三
2 张三
3 张三
------解决方案--------------------
select * from table1 where charindex(',李四,',','+Name+',')>0

------解决方案--------------------
李四怎么变张三了
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
表table1
id Name
1 张三,李四,王五,
2 李四,
3 李四,张三,
需要查询 Name =李四的数据
也就是三条
数据
查询结果格式为:
id Name
1 张三
2 张三
3 张三
------解决方案--------------------
select * from table1 where charindex(',李四,',','+Name+',')>0
------解决方案--------------------
李四怎么变张三了
select id,'李四' as name from table where charindex(',李四,',','+Name+',')>0
------解决方案--------------------
USE test
GO
-->生成表table1
if object_id('table1') is not null
drop table table1
Go
Create table table1([id] smallint,[Name] nvarchar(9))
Insert into table1
Select 1,N'张三,李四,王五,'
Union all Select 2,N'李四,'
Union all Select 3,N'李四,张三,'
DECLARE @Name NVARCHAR(50),@sql NVARCHAR(MAX)
SET @Name=N'李四'
SELECT @sql=ISNULL(@sql+' Union Select ','Select ')+LTRIM(id)+' As id,N'''+REPLACE(Name,',',''' As Name Union all Select '+LTRIM(id)+' As id,N''')+''' As Name' FROM table1
EXEC ('Select * from ('+@sql+') As t Where t.Name='''+@Name+'''')
/*
id Name
----------- ----
1 李四
2 李四
3 李四
*/
------解决方案--------------------
SELECT id,@Name AS Name FROM table1 WHERE CHARINDEX(@Name,Name)>0
------解决方案--------------------
create table tyz(id int ,tname varchar(20))
insert tyz select 1, N'张三,李四,王五'
insert tyz select 2, N'李四'
insert tyz select 3, N'李四,张三'
insert tyz select 4, N'张三'
declare @name varchar(10)
set @name='李四'
select id,@name as name from tyz where substring(tname,charindex(@name,tname),len(@name))=@name