Click here to Skip to main content
15,922,015 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have these tables
SCHOOL- (SchoolID,SchoolName,City,Phone, Description)
PROGRAM- (ProgramID, ProgramName)
COURSE-(CouseID,CourseName)
SCHOOL_PROGRAM_COUSRE - (CourseID,SchoolID,ProgramID,CourseFee,SchoolCourseName)
CATEGORY - (CategoryID,CategoryName)

Now the data which user is entering in the search box are-
1.CategoryName
2.SchoolName
3.CourseName
4.CourseFee

He can enter one,two or maybe three options for search

Now the result which is coming to user are coming from two tables i.e SCHOOL and SCHOOL_PROGRAM_COURSE and the columns which should be displayed to user are-

City, Phone, Description, SchoolCourseName


How to make store procedure for this? I am doing these from last 1 week but failed every time.Please help ASAP.

Thanks
Posted

To do this using a stored procedure and avoiding dynamic SQL, I recommend your parameters have default NULL values

For example:
SQL
@SchoolName varchar(50) = NULL


If the user does not choose a school name, then don't pass it in.

In the SELECT statement, do your joins:

SQL
SELECT S.*, SPC.*
FROM SCHOOL S
INNER JOIN SCHOOL_PROGRAM_COURSE SPC ON S.SchoolID = SPC.SchoolID
INNER JOIN PROGRAM P ON P.ProgramID = P.ProgramID
...


And the magic happens in the WHERE clause:

WHERE (@SchoolName IS NULL OR S.SchoolName = @SchoolName)
  AND (@(other parameter) IS NULL OR ...)


Hope that helps.
 
Share this answer
 
Comments
nidhi30 17-Apr-12 21:37pm    
Thank you so much.
nidhi30 18-Apr-12 5:52am    
I have done like this

@CategoryName nvarchar(100) = null,
@ProgramName nvarchar(50) = null,
@CourseFee money = null,
@CourseName nvarchar(100) = null,
@City nvarchar(30) = null,
@SchoolName nvarchar(100) = null


AS
SELECT S.SchoolName,S.City,S.Suburb,S.Description, SPC.SchoolCourseName
FROM SCHOOL S
INNER JOIN SCHOOL_PROGRAM_COURSE SPC ON S.SchoolID = SPC.SchoolID
INNER JOIN PROGRAM P ON P.ProgramID = P.ProgramID
INNER JOIN COURSE C ON C.CourseID = C.CourseID
INNER JOIN CATEGORY CA ON C.CategoryID = CA.CategoryID


WHERE (@SchoolName IS NULL OR S.SchoolName = @SchoolName)
AND (@CategoryName IS NULL OR CA.CategoryName = @CategoryName)
AND (@CourseName IS NULL OR C.CourseName = @CourseName)
AND (@CourseFee IS NULL OR SPC.CourseFee = @CourseFee)
AND (@City IS NULL OR S.City = @City)


While executing this query returns same row,containing same data four five times :(
Gordon Kushner 18-Apr-12 9:41am    
Add the DISTINCT keyword.

SELECT DISTINCT S.SchoolName,S.City,S.Suburb,S.Description, SPC.SchoolCourseName
Use group by clause on any of the column.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900