During development, you will often encounter queries that require a combination of multiple conditions, such as three tables, Grade Table (GradeId, GradeName), Class (ClassId, ClassName, GradeId ), student (StuId, StuName, ClassId) is required. You can query the Student information in any combination based on the grade Id, class Id, and Student name.
There are more than one method. Here we provide a clever way to use a query. Let's write a process as follows:
Copy codeThe Code is as follows:
Create proc up_select_student_combocondition
@ GradeId int,
@ ClassId int,
@ StuName nvarchar (10)
As
Select s. *, c. classname, g. gradename from student s join class c on s. classid = c. classid join grade g on c. gradeid = g. gradeid
Where
(@ GradeId =-1 or g. gradeid = @ gradeId) and
(@ ClassId =-1 or c. classid = @ classId) and
(@ StuName = ''or s. stuName = @ stuName)
Go
-- So:
Exec up_select_student_combocondition-1,-1, ''-- this is to query all student information
Exec up_select_student_combocondition 2,-1, ''-- this is to query the student information of grade Id 2.
Exec up_select_student_combocondition-, ''-- query the student information with the class Id 4.
Exec up_select_student_combocondition 2, 4, ''-- this is to query the student information of grade Id 2 and class Id 4
-- Etc ....