Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
charlesm
Starting Member
2 Posts |
Posted - 2007-06-20 : 10:57:49
|
| I am creating a stored procedure which receives the following 4 variables. However, VacancySectorID is the only madatory variable. @VacancySectorID int = NULL, (mandatory) @VacancyRegionID int = NULL, optional) @VacancyTypeID int = NULL, (optional) @VacancyKeywords nvarchar(64) = NULL, (optional)My objective is to dynamically build the WHERE statement which in turn will return either one or more of the variables and the required data. The following code works for a single if else but it appears that you cannot have more than one if else statement.Anyones input would be greatly appreciated.SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[sp_Public_GetVacancyListingBySearchCriteria]( @VacancySectorID int = NULL, @VacancyRegionID int = NULL, @VacancyTypeID int = NULL, @VacancyKeywords nvarchar(64) = NULL)AS-- SET NOCOUNT ON;IF @VacancySectorID IS NULL AND @VacancyRegionID Is NULL AND @VacancyTypeID IS NULL AND @VacancyKeywords IS NULLBEGIN SELECT viewVacancies.* FROM viewVacancies WHERE VacancyActive = 1 AND VacancySectorID = @VacancySectorID ORDER BY VacancyPosted DESC, VacancyTitleENDELSEBEGIN SELECT viewVacancies.* FROM viewVacancies WHERE VacancyActive = 1 ORDER BY VacancyPosted DESC, VacancyTitleEND |
|
|
harsh_athalye
Master Smack Fu Yak Hacker
5581 Posts |
Posted - 2007-06-20 : 11:01:50
|
More than one IF...ELSE is definitely allowed.if (condition)begin...endelse if (condition)begin...endelse if ...begin...end Harsh AthalyeIndia."The IMPOSSIBLE is often UNTRIED" |
 |
|
|
charlesm
Starting Member
2 Posts |
Posted - 2007-06-20 : 11:57:33
|
| Thanks for your reply.Is there a more efficient way of doing this then having to write the IF statements for every possible combination / variation? |
 |
|
|
harsh_athalye
Master Smack Fu Yak Hacker
5581 Posts |
Posted - 2007-06-20 : 12:02:05
|
| [code]SELECT viewVacancies.*FROM viewVacanciesWHERE VacancyActive = 1 AND VacancySectorID = Coalesce(@VacancySectorID, VacancySectorID) ANDVacancyRegionID = Coalesce(@VacancyRegionID, VacancyRegionID) AND...ORDER BY VacancyPosted DESC, VacancyTitle[/code]Harsh AthalyeIndia."The IMPOSSIBLE is often UNTRIED" |
 |
|
|
dinakar
Master Smack Fu Yak Hacker
2507 Posts |
Posted - 2007-06-20 : 12:13:23
|
Or even this:SELECT <colulms>FROM <Table >WHERE (@VacancySectorID IS NULL OR VacancySectorID = @VacancySectorID) AND (@VacancyRegionID IS NULL OR VacancyRegionID = @VacancyRegionID) AND .. Dinakar Nethi************************Life is short. Enjoy it.************************http://weblogs.sqlteam.com/dinakar/ |
 |
|
|
|
|
|
|
|