SQL查询无法在VBA中使用。引发自动化错误

时间:2018-11-06 19:29:36

标签: sql-server excel vba

有人可以抬头告诉我下面的VB代码有什么问题

mssql1 = "select TOP 1 [Test Date]from [AllSamples].[dbo].[Results](select TOP 2[Test Date] from [AllSamples].[dbo].[Results] where ([Sample ID] = '" & Split(Sheet1.Cells(i, 6), "-")(0) & "' And [Sample No.] = '" & Split(Sheet1.Cells(i, 6), "-")(1) & "') Order BY [Test Date] DESC) Order BY [Test Date] ASC"

正在获取标签号并将其相应地分为样品ID和样品编号。 请更正查询

1 个答案:

答案 0 :(得分:0)

在您的SQL中,您缺少在TOP 1之后,然后在子查询之前的字段列表以及子查询的别名。应该是这样的:

mssql1 = "select TOP 1 * from " & _ 
" (select TOP 2 [Test Date] from [AllSamples].[dbo].[Results] " & _
" ... Order BY [Test Date] DESC) tmp Order BY [Test Date] ASC"

而且,不要忘记使用参数来代替那些字符串连接,以防止SQL注入攻击和其他字符串问题。