0

我已经看到了几个解决这个 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为日期、日期时间和日期时间2,但没有任何效果。我意识到,当我对日期进行硬编码时,它的工作方式如下:

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

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

4

0 回答 0