0

I have one table called student.Table has 4 column.

Student : Table

Id Name    RollNo  SubjectCode
1  Rani    B0101   1,3,5,7,12
2  Samidha B0102   1,2,4,6,12

I want to find out name of student whose has subjectcode 2.

Query:

select name from student where charindex('2',subjectcode) > 0

But problem occure when subjectcode contain 12.Because 12 contain 2.How to solve it?

Jui Test
  • 2,399
  • 14
  • 49
  • 76

2 Answers2

2

Your query doesn't work because it will match 12 as well as 2.

You can fix this by appending the delimiters on either side:

select name
from student
where charindex(',2,', ','+subjectcode+',') > 0;

That said, you really need another table, which is the association of students and subjects. This table, say StudentSubjects has two important columns: StudentId and SubjectCode. If you had such a table, this query would be quite easy using standard SQL constructs.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Split the CSV value and use the IN clause, like this:

 select name from student where '2' IN Split(',', SubjectCode)

For Split use, for example, the function mentioned in this question.

Community
  • 1
  • 1
Jeroen
  • 60,696
  • 40
  • 206
  • 339