在动态查询中按日期和时间比较两个日期时间

时间:2012-04-12 14:58:33

标签: sql-server-2008 tsql datetime compare

我正在尝试比较两个日期时间,但它在动态查询中不起作用。 为什么部分时间不起作用? 我的代码是这些

    ALTER PROCEDURE [dbo].[testdate]    
    @startDate datetime = null  ,
    @endDate datetime = null,
    @TableName nvarchar(100) ,
    @SearchString NVARCHAR(200)
AS
BEGIN   
    SET NOCOUNT ON; 
    declare @sqlcmd nvarchar(max)


    set  @sqlcmd= 'select * from '+@TableName  +' where '   
    if @startDate is not null and @endDate is not null
    begin

        /*set @sqlcmd=@sqlcmd + ' ( DateLog between'''
        + convert (nvarchar(50), @startDate, 101)
        +''' and ''' 
        --+ convert (nvarchar(50),DATEADD(D,1, @endDate), 101)
        + convert (nvarchar(50), @endDate, 101)
        + ''' ) and '   
        */
        set @sqlcmd=@sqlcmd + ' ( DateLog between @startDate and @endDate ) and '

    end     


    set @sqlcmd=@sqlcmd + '('
    SELECT 
            @sqlcmd  = @sqlcmd + '  [' + SYSCOLUMNS.NAME + '] LIKE N''%'+@SearchString+'%'' or '    
            FROM SYSCOLUMNS 
            WHERE OBJECT_NAME(id) =  @TableName AND TYPE_NAME(SYSCOLUMNS.XTYPE) IN ('VARCHAR','NVARCHAR','CHAR','NCHAR','INT','DECIMAL')

        set @sqlcmd  = @sqlcmd  + '1<>1)'                           
    --print @sqlcmd                                             
    Exec(@sqlcmd)
END

我的表AccountLog有这些字段和数据

     UserName     DateLog
     Salah        2012-04-06 22:06:19.493
     John         2012-08-06 22:06:22.800

此查询为真

 select * from AccountLog where DateLog between '2012-04-06T22:06:19' and '2012-08-06T22:06:23'

但是这个查询没有给我相应的结果

declare @a datetime
declare @b datetime 
set @a = '2012-04-06T22:06:19'  
set @b = '2012-08-06T22:06:23'
exec testdate @a,@b,'AccountLog',N'test' 

2 个答案:

答案 0 :(得分:3)

你应该使用强类型参数并完全抛弃任何转换为​​nvarchar废话。

EDIT 已针对更多需求更改进行了更新。

ALTER PROCEDURE [dbo].[testdate]    
  @startDate    DATETIME = NULL,
  @endDate      DATETIME = NULL,
  @TableName    NVARCHAR(100),
  @SearchString NVARCHAR(200)
AS
BEGIN 
  SET NOCOUNT ON;

  DECLARE @sql NVARCHAR(MAX);
  SET @sql = N'SELECT * FROM dbo.' + QUOTENAME(@TableName) 
    + ' WHERE (1 = 0 ';

  SELECT @sql = @sql + ' OR ' + QUOTENAME(name) + ' LIKE N''%'+@SearchString+'%'''  
    FROM sys.columns WHERE [object_id] = OBJECT_ID('dbo.' + @TableName)
    AND system_type_id IN (56,106,167,175,231,239);

  SET @sql = @sql + ')';

  IF @startDate IS NOT NULL AND @endDate IS NOT NULL
  BEGIN
    SET @sql = @sql + ' AND DateLog BETWEEN @s AND @e';
  END

  EXEC sp_executesql @sql, N'@s DATETIME, @e DATETIME', @startDate, @endDate;
END
GO

答案 1 :(得分:1)

您正在将日期和时间传递给您的过程,但是当您将它们转换为动态SQL时,您使用的是格式101,它会删除时间部分。尝试将101更改为126(代码中有2个位置使用101,请确保更改它们。