我有一个表叫学生。我想要一个学生的名字,其中isactive是1,并且有主题代码1.Like在这里不起作用。它给出了主题代码为11或12的员工的姓名。
id name Isactive subjectcode
1 Shilpa 1 1,2,3
2 Manasi 1 11
3 kamal 1 12,3
4 Hans 0 1,2
5 Rupali 1 1,11,12
答案 0 :(得分:0)
首先创建此功能
create function [dbo].[fnSplitString]
(
@string nvarchar(max)
,@delimiter char(1) = ','
)
returns @t table(string nvarchar(max))
as
begin
declare @pos int
declare @piece varchar(500)
if right(rtrim(@string),1) <> @delimiter
set @string = @string + @delimiter
set @pos = patindex('%' + @delimiter + '%' , @string)
while @pos <> 0
begin
set @piece = left(@string, @pos - 1)
insert @t
select @piece
set @string = stuff(@string, 1, @pos,'')
set @pos = patindex('%' + @delimiter + '%' , @string)
end
return
end
然后运行
DECLARE @result TABLE (id Int,name Varchar(50),isactive Bit, subjectCode Varchar(200))
INSERT INTO @result
SELECT 1 , 'Shilpa' , 1 , '1,2,3'
INSERT INTO @result
SELECT 2 , 'Manasi' , 1 , '11'
INSERT INTO @result
SELECT 3 , 'kamal', 1 , '12,3'
INSERT INTO @result
SELECT 4 , 'Hans' , 0 , '1,2'
INSERT INTO @result
SELECT 5 , 'Rupali' , 1 , '1,11,12'
SELECT * FROM @result WHERE isactive=1 AND
(11 IN(SELECT * FROM [dbo].[fnSplitString](subjectCode,','))
OR 12 in
(SELECT * FROM [dbo].[fnSplitString](subjectCode,',')))
答案 1 :(得分:0)
你可以尝试下面的SQL查询
DECLARE @result TABLE (id Int,name Varchar(50),isactive Bit, subjectCode Varchar(200))
INSERT INTO @result
SELECT 1 , 'Shilpa' , 1 , '1,2,3'
INSERT INTO @result
SELECT 2 , 'Manasi' , 1 , '11'
INSERT INTO @result
SELECT 3 , 'kamal', 1 , '12,3'
INSERT INTO @result
SELECT 4 , 'Hans' , 0 , '1,2'
INSERT INTO @result
SELECT 5 , 'Rupali' , 1 , '1,11,12'
select * from @result where Isactive = 1 and (','+ subjectcode + ',') like '%,' + '1' + ',%'
答案 2 :(得分:0)
请使用以下条件而不是像
where CHARINDEX('1,',subjectcode) > 0 or CHARINDEX(',1',subjectcode) > 0
这样可行。