Working with datetime with dynamic query in SQL Server

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

    I'd like to see your variable definitions but I suspect it's because @FROMDATE and @TODATE are datetime and you're using them in a string concatenation statement. Thus you can fix it by:

    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(VARCHAR(10),'+CAST(@FROMDATE as varchar(15))+', 101) and CONVERT(VARCHAR(10), DATEADD(DD,1,'+CAST(@TODATE as varchar(15))+'), 101)'
    

    However better solutions are:

    1. Don't use dynamic SQL at all, maybe @TABLE doesn't vary that much and you can union them in to a view or something
    2. Pass the parameters directly in to sp_executeSQL and thus preserve their types e.g.

    SET @SQL1 = 'SELECT B.FacId, B.FacName, B.BookCode, B.BookName, B.Quantity, B.TillDate AS TILLDATE FROM '+@TABLE+' B WHERE B.TillDate BETWEEN @inFROMDATE and @inTODATE'

    EXEC SP_EXECUTESQL @SQL1,'@inFROMDATE datetime, @inTODATE',@inFromDate = @FROMDATE, @inTODATE = @TODate

提交回复
热议问题