sql server - date filtering in dynamic SQL -
set @vsqlfilters = '(abra.start_date !> ' + cast(@denddate varchar(26)) + ' or abra.end_date !< ' + cast(@dstartdate varchar(26)) + ')';
i want parameters @dstartdate , @denddate keep quotes around them. currently, they're typed in manually end user quotes around them. right now, get
(abra.start_date !> 2013-05-01 or abra.end_date !< 2011-04-05)
in query instead of
(abra.start_date !> '2013-05-01' or abra.end_date !< '2011-04-05').
since thrown dynamic sql query, need @denddate , @dstartdate cast strings. want treat dstartdate , denddate dates not integers. don't see how can sql compare dates.
thanks!
put doubled-up single quotes anywhere within statement want single quote appear:
set @vsqlfilters = '(abra.start_date !> ''' + cast(@denddate varchar(26)) + ''' or abra.end_date !< ''' + cast(@dstartdate varchar(26)) + ''')';
however, there no need this. sp_executesql
can use parameters:
declare @sql nvarchar(max); set @sql = 'select * dbo.abra abra abra.start_date <= @denddate' + ' , abra.end_date >= @dstartdate'; exec sp_executesql @sql, n'@dstartdate datetime, @denddate datetime', @dstartdate, @denddate;
this is, in mind, better practice. may offer better performance through execution plan reuse (or may not).
i recommend not use inequality operators !
, !<
, , !>
. make hard others read , comprehend code. use <>
, >=
, , <=
.
last, sure wanted or
in filter? may missing something.
Comments
Post a Comment