运行动态sql时将表达式转换为数据类型datetime的算术溢出错误

时间:2018-03-11 02:24:33

标签: sql sql-server dynamic-sql sqldatetime sql-convert

我已经看到了这个SQL错误(8115)的几个解决方案,但似乎没有一个对我有用。我认为它是因为我使用的是动态SQL脚本。我从具有相同结构的多个服务器动态提取数据并插入到中央表中。我遇到的问题是,当使用动态脚本时,如下所示,我一直收到错误。

DECLARE @SQL NVARCHAR(4000);
DECLARE @counter int = 0;
DECLARE @scriptcnt int;
declare @startdate varchar(8) = '20180304';-- cast(@startdate as date)
declare @enddate varchar(8) = '20180305';--cast(@enddate as date)

select srv.name
INTO #ServerNames    
from sys.servers srv
where name like 'Pulse%'
order by 1;

select name,right(name,5) store_no
into #locationCode
from #SERVERNAMES;


With ServerCTE AS (
SELECT Root=NAME + '.[POS].[dbo].' 
FROM #SERVERNAMES)
Select 
Root + '[Customer]' as Customer
INTO #Tables
from ServerCTE

Begin Transaction
delete from WFLCustomerMaster
--where Location_Code = '16450'--@storeNum
commit;

select 
'
        Begin TRY
        Begin Transaction
        Insert into WFLCustomerMaster(.....)
    SELECT .....
        FROM '+ Customer + '
        where [Last_Order_Date] between '+ @startdate+ ' and '+ @enddate+ ' [This line is the issue]
        commit;
        END TRY
        BEGIN CATCH
        SELECT 
                ERROR_PROCEDURE() as nameofprocedure,
                ERROR_NUMBER() AS errorcode,
                error_line() as errorline,
                ERROR_MESSAGE() as errormessage

        END CATCH' as Customer into #query
from #Tables a, #locationCode b
where left(a.Customer,13) = b.name

select @scriptcnt = count(*) from #query

while @counter < @scriptcnt
begin
    set @counter = @counter + 1
    SET @SQL = (SELECT Customer FROM 
                (SELECT  ROW_NUMBER() OVER (ORDER BY Customer) AS ID, Customer FROM #query) MySQL
                WHERE ID=@Counter )
    EXEC SP_EXECUTESQL @SQL
end

我尝试将@startdate@enddate转换为date,datetime和datetime2,但没有任何效果。 我意识到,当我硬编码它的工作日期时,如下所示:

...'where [Last_Order_Date] between ''20180306'' and ''20180306'''....

所以我知道这部分是问题所在。有人可以帮忙吗?

0 个答案:

没有答案