Allow to Pass Optional Parameters to a Stored Procedure

Mount Carrigain NH 1427mIf you have several search boxes on a Web page and some boxes can be blank, how do you pass values of those search boxes into SQL stored procedure (SP)?  Pass them as empty strings, and then process the values here in SP.

In this example a series of IF statements build an SQL string @sql, and then EXEC statement executes the resulting SQL command.

USE [YourDB]
/****** Object:  StoredProcedure [dbo].[qTasksSubstituteNULLS]
        Script Date: 12/10/2019 21:30:13 ******/
-- =============================================
-- Author:  Yuor Name
-- Create date: 2019-12-09 WE
-- Description: Substitute String Params with Bool
-- =============================================
ALTER PROCEDURE [dbo].[qTasksSubstituteNULLS]
-- Add the parameters for the stored procedure here
@taskDoneCHAR nvarchar(16) = '*ALL',
@taskCategoryCHAR nvarchar(16) = '*ALL'
@sql nvarchar(1000) = N'SELECT * FROM tTaskMaster ',
@taskDoneYN bit = NULL,
@taskCategory nvarchar(16) = NULL;
-- Begin substitutin CHAR with BOOL parameters
IF @taskDoneCHAR = 'Open' SET @taskDoneYN = 0
IF @taskDoneCHAR = 'Completed' SET @taskDoneYN = 1
IF @taskCategoryCHAR != '*ALL' SET @taskCategory = @taskCategoryCHAR
IF @taskDoneYN IS NOT NULL  AND @taskCategory IS NOT NULL
SET @sql = @sql + N' WHERE taskDoneYN = @taskDoneYN AND taskCategory = @taskCategory '
IF @taskDoneYN   IS NOT NULL SET @sql = @sql + N' WHERE taskDoneYN   = @taskDoneYN '
IF @taskCategory IS NOT NULL SET @sql = @sql + N' WHERE taskCategory = @taskCategory '
SET @sql = @sql + N' UNION SELECT * FROM tTaskMaster WHERE taskID = 10 '
SET @sql = @sql + N' ORDER BY taskPriority, taskDateDue '
EXEC sp_ExecuteSQL @sql, N'@taskDoneYN bit, @taskCategory nvarchar(16)', @taskDoneYN, @taskCategory


Conclusion: Note that string PARAMETERS are controlling the way SQL select statement is built. Also note that UNION is used to add one *EMPTY* row that will allow GridView to display footer (INSERT) row, even if no records were found.

(Visited 591 times, 3 visits today)

Be the first to comment

Your question, correction or clarification Ваш вопрос, поправка или уточнение

Editor on duty will review your comment. Can't wait? Discuss your topic right now in forums, if you register and login.     Required fields are marked with * Ваше послание пойдет на просмотр в редакцию. Не можете ждать? Обсудите ваш вопрос прямо сейчас в форуме Русский Круг , ecли вы зарегистрируетесь и войдёте под своим именем.     Поля, обязательные для заполнения, помечены *
* *