|
|
|||||||||
|
|||||||||
|
|||||||||
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Free Web 2.0 Code Generator! Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!
|
|
#1
|
|||
|
|||
|
Stored Procedures - Building dynamic sql queries into a stored procedure
Hi i have a page whereby the user can make a search based on three things, they are a textbox(userName), dropdownlist(subcategoryID), and region (regionID). The user does not have to select all three, he or she can enter a name into the textbox alone and make the search or enter a name into the textbox and select a dropdownlist value, my question is how can i build this procedure, I tried this but it didnt work;
Code:
ALTER PROCEDURE [dbo].[stream_UserFind] ( @userName varchar(100), @subCategoryID INT, @regionID INT ) AS declare @StaticStr nvarchar(5000) set @StaticStr = 'SELECT DISTINCT SubCategories.subCategoryID, SubCategories.subCategoryName, Users.userName ,UserSubCategories.userID FROM Users INNER JOIN UserSubCategories ON Users.userID= UserSubCategories.userIDINNER JOIN SubCategories ON UserSubCategories.subCategoryID = SubCategories.subCategoryID WHERE UserName like @UserName' if(@subCategoryID <> 0) set @StaticStr = @StaticStr + ' and SubCategories.subCategoryID = @subCategoryID ' if(@regionID <> 0) set @StaticStr = @StaticStr + ' and SubCategories.RegionId = @regionID ' exec sp_executesql @StaticStr ) |
|
#2
|
|||
|
|||
|
Code:
ALTER PROCEDURE [dbo].[stream_UserFind] ( @userName varchar(100)=NULL, @subCategoryID INT=NULL, @regionID INT =NULL ) AS SELECT DISTINCT SubCategories.subCategoryID, SubCategories.subCategoryName, Users.userName ,UserSubCategories.userID FROM Users INNER JOIN UserSubCategories ON Users.userID= UserSubCategories.userIDINNER JOIN SubCategories ON UserSubCategories.subCategoryID = SubCategories.subCategoryID WHERE (UserName like @UserName OR ISNULL(@UserName,'')='') and (SubCategories.subCategoryID = @subCategoryID OR ISNULL(@subCategoryID,'')='') and (SubCategories.RegionId = @regionID OR ISNULL(@regionID,'')='') GO Make sure you pass '' or NULL as value from your form controls when user dont select a value from them. |
![]() |
| Viewing: ASP Free Forums > Database > Microsoft SQL Server > Stored Procedures - Building dynamic sql queries into a stored procedure |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|
|
|
|