我下面的动态查询有效,但想知道我下面的内容是否可以优化,或者是否有更好的方法。
我有一个网页表单,用户输入位置和收集日期。对于收集的日期,我收集了收集日期和收集日期。用户离开收集日期时收集空白,在这种情况下,它将执行大于收集日期的任何操作。
注意我是如何做IS NOT NULL和1 = 1的。还想知道动态SQL是否是最好的方法,或者是否有更简单的方法。
DECLARE @sql varchar(max);
SET @sql = 'SELECT * from tblProgram WHERE 1=1'
IF (@Location IS NOT NULL)
BEGIN
SET @sql = @sql + ' AND Location = ' + @Location
END
IF (@FromDateCollected IS NOT NULL AND @ToDateCollected IS NOT NULL)
BEGIN
SET @sql = @sql + ' AND pw.DateCollected >= ' + QUOTENAME(convert(varchar, @FromDateCollected,101),'''')
+ ' AND pw.DateCollected <= ' + QUOTENAME(convert(varchar, @ToDateCollected,101),'''')
END
ELSE IF (@FromDateCollected IS NOT NULL AND @ToDateCollected IS NULL)
BEGIN
SET @sql = @sql + ' AND pw.DateCollected >= ' + QUOTENAME(convert(varchar, @FromDateCollected,101),'''')
END
exec(@sql)
答案 0 :(得分:4)
你可以做ta.speot.is注释使用静态SQL并执行
WHERE x is null or x > date_column?
但是,如果您坚持使用动态SQL,则应使用sp_executeSQL
的参数化SQL语句它更易于阅读,您不必使用引号,并且您受到SQL注入的保护
DECLARE @Location int
DECLARE @FromDateCollected datetime
DECLARE @ToDateCollected datetime
SET @ToDateCollected = '1/02/2012'
DECLARE @sql nvarchar(max)
DECLARE @ParmDefinition nvarchar(max)
SET @ParmDefinition = N'@Location int , @FromDateCollected datetime, @ToDateCollected datetime ';
SET @sql = N'SELECT * from tblProgram WHERE 1=1'
IF (@Location IS NOT NULL)
BEGIN
SET @sql = @sql + N' AND Location = @Location'
END
IF (@FromDateCollected IS NOT NULL AND @ToDateCollected IS NOT NULL)
BEGIN
SET @sql = @sql + N' AND pw.DateCollected >= @FromDateCollected '
+ N' AND pw.DateCollected <= @ToDateCollected '
END
ELSE IF (@FromDateCollected IS NOT NULL AND @ToDateCollected IS NULL)
BEGIN
SET @sql = @sql + N' AND pw.DateCollected >= @FromDateCollected'
END
exec sp_executesql @SQL, @ParmDefinition, @Location = @Location,
@FromDateCollected = @FromDateCollected,
@ToDateCollected = @ToDateCollected