sql查询

ca1c2owp  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(270)

当下面的sql查询包含一个日期时,我可以运行它。当我引入第二个日期时,不会返回结果。
我还利用 DD/MM/YY 格式,但只有一个日期。
我正在使用Office2010并连接到oracle sql数据库。

Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

ConnectionString = SQLConnect 'This is a function that resolves to the connection string
cnn.Open ConnectionString
cnn.CommandTimeout = 180

StrQuery = "select  ref, date from records  where  date > '10-MAY-20'  And date < '13-MAY-20'"

rst.Open StrQuery, cnn

ThisWorkbook.Sheets("Sheet 1").Range("A2").CopyFromRecordset rst
rst.Close
cnn.Close

我尝试将查询修改为“select noteno,trandate from records where date between'10-may-20'and'13-may-20'”。
当使用一个日期时,这两个查询都在oraclesqldeveloper中工作。
“select noteno,trandate from records where date like'%may-20'”在通过vba运行时也不起作用(但在oracle sql developer中很好)。

6tdlim6h

6tdlim6h1#

其中日期>20年5月10日和日期<20年5月13日 '10-MAY-20' 不是日期,而是字符串。日期没有任何格式,根据特定于语言环境的nls设置,它将使用 TO_CHAR 以及适当的格式掩码。
另外,你应该避免使用两位数 YY 这是y2k病毒开始的全部原因。始终使用 YYYY 格式。
要将字符串转换为日期:
使用 TO_DATE 和适当的格式掩码:

where  date_col > TO_DATE('10-MAY-2020', 'DD-MON-YYYY')  
and    date_col < TO_DATE('13-MAY-2020', 'DD-MON-YYYY')

或者,使用 ANSI date literal 它使用固定格式 'YYYY-MM-DD' :

where  date_col > DATE '2020-05-10' and date < DATE '2020-05-13'

还有一件事, DATE 是甲骨文的保留字,可以看文档。也许,您使用的是带引号的标识符 "date" i、 在保留字周围用双引号。
我不明白为什么不使用'10-may-20',因为这是oraclesql开发人员所要求的格式
这可能是因为sqldeveloper的nls设置为 'DD-MON-YY' ,因此当您以该格式传递日期时,它不会隐式转换为日期。但是,如果更改格式,它将不起作用:

alter session set NLS_DATE_FORMAT = 'YYYY-MM-DD';
arknldoa

arknldoa2#

日期不是字符串,如果处理表示日期的字符串,则由驱动程序或数据库将其解释为日期。甲骨文期望 TO_DATE -函数,对于sql server,如果使用正确的格式,则可以不使用函数编写它。对于其他数据库,可能会有所不同。
我一直主张使用 ADODB.Parameter 传递参数。这意味着要编写更多的代码,但在参数格式化(字符串、浮点数等也是如此)和防止sql注入方面没有更多麻烦。你需要创建一个 ADODB.Command 对象加1 ADODB.Parameter 传递给数据库的每个参数。在查询中,只需将参数值替换为 ? ```
dim d1 as Date, d2 as Date
d1 = CDate("2020-05-10") ' Control of the date is completely in your hand.
d2 = CDate("2020-05-13")

StrQuery = "select ref, date from records where date > ? And date < ?"
' Create command
Dim cmd as New ADODB.Command
Set cmd.ActiveConnection = cnn
cmd.CommandText = StrQuery

' Create 2 parameter of type Date and pass the date values
Dim param as ADODB.Parameter
Set param = cmd.CreateParameter("p1", adDate, adParamInput, , d1)
cmd.Parameters.Append param
Set param = cmd.CreateParameter("p2", adDate, adParamInput, , d2)
cmd.Parameters.Append param

Set rst = cmd.Execute

相关问题