Working with datetime with dynamic query in SQL Server

后端 未结 7 2831
野性不改
野性不改 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:06

    I think this might work:

     DECLARE @tempdate datetime
     SET tempdate =DATEADD(DD,1,@TODATE)
     SET @SQL1 = 'SELECT B.FacId, B.FacName, B.BookCode, B.BookName, B.Quantity,'''+  cast     (B.TillDate as VARCHAR(50))+''' AS TILLDATE FROM '+@TABLE+' B WHERE B.TillDate BETWEEN '''+cast(@FROMDATE as VARCHAR(50))+''' and  '''+cast(@tempdate as VARCHAR(50))'''
    
     EXEC SP_EXECUTESQL @SQL1 
    

提交回复
热议问题