Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored procedure to select between dates?

I am writing a stored proc to Select information, i would like it to only select between dates?

This is what it looks like now:

ALTER PROCEDURE [dbo].[AutoCompleate] 
 @DateFrom datetime,
 @DateTo datetime,
 @SearchField varchar(50)
 AS

 -- V1.0 : ShaunM : 15 jun 2012
    --  AutoComplete textbox

 exec ('
 SELECT DISTINCT ' +
 @SearchField + ' FROM SchemaAudit 
             ORDER BY ' + @SearchField +' ASC')

I want the select to run for entry's into the database between @DateTo and DateFrom, Does any one know how to do this?

like image 218
Pomster Avatar asked Jul 01 '26 00:07

Pomster


1 Answers

Instead of exec you should be using sp_executesql which allows for use of parameters, avoiding a risk of Sql injection and avoiding potential issues with dates passed as strings. First parameter is a query, second is a list of parameters and their types and the rest are parameter values.

alter PROCEDURE [dbo].[AutoCompleate] 
     @DateFrom datetime,
     @DateTo datetime,
     @SearchField varchar(50)
     AS

     -- V1.0 : ShaunM : 15 jun 2012
        --  AutoComplete textbox

    declare @sql nvarchar(max)
    set @sql = 'SELECT DISTINCT ' 
             + quotename(@SearchField)
             + ' FROM SchemaAudit'
             + ' WHERE [Date] between @from AND @to ORDER BY '
             + quotename(@SearchField)
             + ' ASC'

     exec sp_executesql @sql, 
                        N'@from datetime, @to datetime', 
                        @from = @DateFrom, @to = @DateTo

Now, about start and end dates, what exactly you want to do?

like image 195
Nikola Markovinović Avatar answered Jul 03 '26 13:07

Nikola Markovinović



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!