如何在SQL查询中创建异常(Access to Excel)

问题描述 投票:1回答:1

我从Access表中获取一些数据到Excel工作表,它们取决于一些参数。访问表上的我的数据列表包括例如:

1-x branch
2-y branch
3-z branch
4-t commercial branch
5-r commercial branch
6-w corporate branch
7-g corporate branch

在Excel VBA上,如果我想检索所有数据,我正在创建一个SQL查询,如:

sql = "select * from [table] where [Branches] like "%"

如果我只想检索商业分支数据:

sql = "select * from [table] where [Branches] like '%" & "commercial" & "%'"

如果我只想检索公司分支数据:

sql = "select * from [table] where [Branches] like '%" & "corporate" & "%'"

这是问题所在。如果我想检索除公司和商业分支以外的数据,我该怎么办?我们可以创建什么样的SQL查询?

非常感谢。


这是我的坏事,我可以解释得更清楚。在创建查询之前,我使用的参数如下:

Select Case main.Range("D6").Value
Case "ALL"
brnch = "%"
Case "CORPORATE"
brnch = "%" & "CORPORATE" & "%"
Case "COMMERCIAL"
brnch = "%" & "COMMERCIAL" & "%"
End Select

我的查询实际上是这样的:

sql = "select * from [table] where [Branches] like '" & brnch & "'"

现在,我可以做什么来检索没有广告和企业的分支机构。

sql excel vba access-vba
1个回答
3
投票

你可以使用not like

sql = "select * from [table] where Branches not like '%corporate%' and branches not like '%commercial%'";

如果要在MS Access中运行此代码,通配符是不同的,字符串分隔符是双引号:

sql = "select * from [table] where Branches not like ""*corporate*"" and branches not like ""*commercial*""";
© www.soinside.com 2019 - 2024. All rights reserved.