SQL Server cleverly solves multiple conditional combination query _mssql

Source: Internet
Author: User
Development often encounter the need for a variety of conditional combination of inquiries, such as three tables, Grade table grade (Gradeid,gradename), Class Class (Classid,classname,gradeid), Student table student (Stuid, STUNAME,CLASSID), now requires that can be based on grade ID, class ID, student name, these three conditions can be any combination of query student information.

There is more than one, and here's a clever way to use a query, and we'll write a process that reads:
Copy Code code 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

--Then:
exec up_select_student_combocondition-1,-1, '--it's all about the student information.
exec up_select_student_combocondition 2,-1, '--this is the student information for the Grade ID 2.
exec up_select_student_combocondition-1,4, '--this is the student information that queries class ID 4
EXEC up_select_student_combocondition 2, 4, '--this is a student message with a grade ID of 2 and a class ID of 4
--etc .....
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.