我在VBA中遇到问题,执行SQL查询会生成运行时错误3075.
在Microsoft SQL Server管理器中运行相同的查询,我没有遇到任何问题,并返回所需的结果。
我尝试使用Debug.print打印sql-query(如此处所示:https://stackoverflow.com/a/3136299/4474367)以查看查询的外观 - 它看起来没问题,并且可以很好地粘贴到SQL Server Manager中。
我正在做的是选择某个经销商的总行数(调查回复)(以及其他一些标准),将结果除以A2 = 5的行总数(使用子查询)然后乘以100得到A2 = 5的百分比。
你们认为什么是错的? Access中是否有任何限制我可能没有考虑过?只有子查询才会显示在错误消息中。
这是我的查询(我使用换行符将其剪切一下以便于阅读):
SELECT DealerCode,
(SELECT CAST(COUNT(A2) AS FLOAT)
FROM dbo_Service
WHERE A2 = 5
AND MarketCode = 'CA'
AND DealerCode = '3140'
AND CompleteDate BETWEEN '2014-01-20'
AND '2015-01-20') / COUNT(*) * 100 AS TopBox
FROM dbo_Service
WHERE DealerCode = '3140'
AND MarketCode = 'CA'
AND CompleteDate BETWEEN '2014-01-20' AND '2015-01-20'
GROUP BY DealerCode;
Uncut版本(与上面完全相同,但没有换行符):
SELECT DealerCode, (SELECT CAST(COUNT(A2) AS FLOAT) FROM dbo_Service WHERE A2 = 5 AND MarketCode = 'CA' AND DealerCode = '3140' AND CompleteDate BETWEEN '2014-01-20' AND '2015-01-20') / COUNT(*) * 100 AS TopBox FROM dbo_Service WHERE DealerCode = '3140' AND MarketCode = 'CA' AND CompleteDate BETWEEN '2014-01-20' AND '2015-01-20' GROUP BY DealerCode;
VBA Snippet,查询程序:
strSQL = "SELECT DealerCode, (SELECT CAST(COUNT(A2) AS FLOAT) FROM dbo_Service WHERE A2 = 5 AND MarketCode = 'CA' AND DealerCode = '3140' AND CompleteDate BETWEEN '2014-01-20' AND '2015-01-20') / COUNT(*) * 100 AS TopBox FROM dbo_Service WHERE DealerCode = '3140' AND MarketCode = 'CA' AND CompleteDate BETWEEN '2014-01-20' AND '2015-01-20' GROUP BY DealerCode;"
Debug.Print strSQL
Set rs = db.OpenRecordset(strSQL)
topBox = rs!topBox
db.Close
以下是我收到的错误图片的链接
最好的问候和感谢阅读!
答案 0 :(得分:3)
这是SQL Server方言查询,而不是MS Access。您需要在SQL Server上执行查询,这是一个传递查询。有关详细信息和解决方案,请参阅SQL Server Passthrough query stored into an Access VBA recordset。
答案 1 :(得分:2)
因此,在遵循HansUp的回答之后,我编辑了我的SQL查询并用Cdbl替换了CAST。
现在看起来像这样:
"SELECT DealerCode, ((SELECT CDbl(COUNT(A2)) FROM dbo_Service WHERE A2 = 5 AND MarketCode = 'CA' AND DealerCode = '3140' AND CompleteDate BETWEEN '2014-01-20' AND '2015-01-20') / COUNT(*)) * 100 AS TopBox FROM dbo_Service WHERE DealerCode = '3140' AND MarketCode = 'CA' AND CompleteDate BETWEEN '2014-01-20' AND '2015-01-20' GROUP BY DealerCode;"
当更改为Cdbl而不是CAST时,我还必须在CAST之后删除“AS FLOAT”。
简而言之,它看起来像这样:
SELECT CDbl(COUNT(A2))
而不是:
SELECT CAST(COUNT(A2) AS FLOAT)
快速修复工作!
感谢您的回答!