I have UI where a user can search on optional parameters.I am writing a SP and as a testing database I am using AdventureWorks.
For some reasons I dont seem to find a way how to include
Where ModifiedDate between ”’ + @Fromdate + ”’ And ”’+ @ToDate + ””)
in my existing SP.Can you help?
My sp looks like this
ALTER PROCEDURE SearchPerson_Dynamic
(
@FirstName NVARCHAR(50) = NULL,
@LastName NVARCHAR(50) = NULL,
@EmailAddress NVARCHAR(50) = NULL,
@Phone NVARCHAR(25) = NULL,
@FromDate DATETIME =NULL,
@ToDate DATETIME =NULL
AS
DECLARE @sSQL NVARCHAR(MAX), @Where NVARCHAR(1000) = ''
SET @sSQL = 'SELECT * FROM [Person].[Contact]'
IF @FirstName is not null
SET @Where = @Where + 'AND FirstName = @_FirstName '
IF @LastName is not null
SET @Where = @Where + 'AND LastName = @_LastName '
IF @EmailAddress IS NOT NULL
SET @Where = @Where + 'AND EmailAddress = @_EmailAddress '
IF @Phone IS NOT NULL
SET @Where = @Where + 'AND Phone = @_Phone '
-- NEED TO INTEGRATE A SEARCH BETWEEN @FromDate and @ToDate
IF LEN(@Where) > 0
SET @sSQL = @sSQL + 'WHERE ' + RIGHT(@Where, LEN(@Where)-3)
EXEC sp_executesql @sSQL,
N'@_FirstName VARCHAR(50),
@_LastName VARCHAR(50),
@_EmailAddress VARCHAR(50),
@_Phone NVARCHAR(25)',
@_FirstName = @FirstName,
@_LastName = @LastName,
@_EmailAddress = EmailAddress,
@_Phone = @Phone
MISSING @FROMDate and @ToDate --HOW DO i DO IT HERE
One thing I have not done is that some fields EG Surname the user can select “ALL” in the UI from the drop down. How would I implement a search where I dont have an exact parameter?
Thanks again for your help
If I was to rewrite your stored proc, I would do the following
This is better as its not executing text for the stored procedure and could be optimized.
If you want to use the dynamic sql, you could cast the date to a normal string, ie