Working with datetime with dynamic query in SQL Server

后端 未结 7 2828
野性不改
野性不改 2021-02-20 11:56

I am using a dynamic query wherein I want to use the variable which holds the datetime, whenever I execute the query it says cannot convert datetime from string, when I cast tha

相关标签:
7条回答
  • 2021-02-20 12:23

    Try this:

    declare @sql1 varchar(max)
    declare @table sysname
    declare @FROMDATE datetime
    declare @TODATE datetime
    
    set @table = 'MyTable'
    set @FROMDATE = GETDATE()
    set @ToDATE = GETDATE()
    
    
    SET @SQL1 = 'SELECT B.FacId, B.FacName, B.BookCode, B.BookName, B.Quantity, 
    CONVERT(VARCHAR(10), B.TillDate, 104) AS TILLDATE FROM '+@TABLE+' B
    WHERE B.TillDate BETWEEN CONVERT(Datetime,''' + CONVERT(VARCHAR(10),@FROMDATE, 101) 
    + ''', 101) and CONVERT(DATETIME,'''+ CONVERT(VARCHAR(10), DATEADD(DD,1,@TODATE), 101) + ''', 101)'
    
    
    print @sql1
    

    But look at Joel Mansford's answer to avoid the double conversion.

    0 讨论(0)
提交回复
热议问题