Home Forums SQL Server 2008 SQL Server Newbies Dynamic WHERE statement if stored procedure parameter is null RE: Dynamic WHERE statement if stored procedure parameter is null

  • Oh be careful here Laurie. You suggested using dynamic sql which is a good choice here. However you committed a cardinal sin. You allowed for the parameters to be executed. This is now a sql injection vulnerability. You should instead use parameters to your dynamic sql.

    Here is a full working example.

    create table #table1

    (

    StartDate datetime,

    EndDate datetime

    )

    insert #table1

    select '1/15/1900', '2/1/1900'

    declare @sql nvarchar(max),

    @Startdate nvarchar(10),

    @Enddate nvarchar(10);

    set @sql = 'select * from #table1';

    set @Startdate = '01/01/1900';

    set @Enddate = '01/01/1901';

    if @Startdate > '' AND @Enddate > ''

    set @sql = @sql + ' where Startdate >= @Startdate and Enddate <= @Enddate'

    print @sql

    exec sp_executesql @sql, N'@Startdate datetime, @EndDate datetime', @Startdate = @Startdate, @Enddate = @Enddate

    drop table #table1

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/