每当我尝试在数据库的旧副本上运行它时,它就会完美运行。
DECLARE @CompanyName AS VARCHAR(50)
DECLARE @SQLCommand AS VARCHAR(MAX) = ''
DECLARE companycursor CURSOR FOR SELECT
REPLACE([Name],'.','_') as[Name]
FROM
Company;
OPEN companycursor
FETCH companycursor INTO @CompanyName
WHILE @@FETCH_STATUS = 0
BEGIN
IF @SQLCommand <> '' SET @SQLCommand += 'UNION ALL'
SET @SQLCommand +=
'
SELECT [Company Name] = ''' + @CompanyName + ''', *
FROM [' + @CompanyName + '$Sales Line]
INNER JOIN [' + @CompanyName + '$Sales Header]
ON [' + @CompanyName + '$Sales Line].[Document No_] = [' + @CompanyName + '$Sales Header].[No_]
WHERE (YEAR([' + @CompanyName + '$Sales Header].[Posting Date])> CAST(2016 AS int)-1
OR YEAR([' + @CompanyName + '$Sales Header].[Posting Date])= CAST(2016 AS int)-1 AND MONTH([' + @CompanyName + '$Sales Header].[Posting Date])> 12-CAST(3 AS int)
OR YEAR([' + @CompanyName + '$Sales Header].[Posting Date])= CAST(1753 AS int) AND YEAR([' + @CompanyName + '$Sales Header].[Order Date])> CAST(2016 AS int)-1
OR YEAR([' + @CompanyName + '$Sales Header].[Posting Date])= CAST(1753 AS int) AND YEAR([' + @CompanyName + '$Sales Header].[Order Date])= CAST(2016 AS int)-1 AND MONTH([' + @CompanyName + '$Sales Header].[Order Date])> 12-CAST(3 AS int))
AND YEAR([' + @CompanyName + '$Sales Header].[Posting Date]) < CAST(2017 AS int)+1
'
FETCH companycursor INTO @CompanyName
END;
EXEC(@SQLCommand)
--PRINT @SQLCommand
CLOSE companycursor
DEALLOCATE companycursor
但是,当我尝试在实时数据库上运行它时会出错。
Msg 8114,Level 16,State 5,Server VES-SQL01,Line 2 将数据类型nvarchar转换为数字时出错。
答案 0 :(得分:0)
通过用SELECT替换EXEC,然后在查询窗口中复制/粘贴输出并执行,这些调试非常好。您可以多次双击红色SQL Server错误,光标将直接跳到问题。
不是解决方案,而是我认为非常雄辩地找到解决方案的方法。