VBScript中基于输入日期的SQL查询

时间:2019-01-17 19:18:54

标签: vbscript asp-classic

我有一个VBscript可以查询数据库以根据移位来提取数据,例如墓地,白天和秋千。我只需要在1-6-2019之后的几天将时间减少一个小时即可。

我尝试过的解决方案是扩展我的if语句并添加一个AND函数,但是由于第一个if语句仍然为真,因此无法正常工作。

dim intCoilCount, intTotalSeconds,intSeconds,strDate,strShift

'SQL="select timeStamp, coil_number, entry_gaptime,thickness,width_in,grade from TABLEEEE by timeStamp"
strShift=Request.Form("SHIFT")
strDate=Request.Form("StartDate")

'if date is greater than 2-22-2006 (switchover date) use SCALEFACTOR
'-----start-----------------
if datediff("d",strDate,cdate("2/22/2006")) <= 0 then
  SCALEFACTOR=30000.0 / 50.0
else
  SCALEFACTOR=1
end if

'-----end-----------------

'Fixed scale factor problem
'-----start-----------------
SCALEFACTOR=1
'-----end-----------------

SQL="select timeStamp, coil_number, entry_gaptime,thickness,width_in,grade from entryCoilData" 
if strShift="graveyard" then
    SQL = SQL & " where timestamp > '" & cdate(strDate)-1 & " " & "11:00PM" & "'" & _
                " and timestamp <= '" & strDate & " " & "7:00AM" & "'"

elseif strShift="graveyard" and strDate >= cdate(1-6-2019) then
    SQL = SQL & " where timestamp > '" & strDate & " " & "10:00AM" & "'" & _
                " and timestamp <= '" & strDate & " " & "2:00PM" & "'"

elseif strShift="day" then
    SQL = SQL & " where timestamp > '" & strDate & " " & "7:00AM" & "'" & _
                " and timestamp <= '" & strDate & " " & "3:00PM" & "'"

elseif strShift="day" and strDate >= cdate(1-6-2019) then
    SQL = SQL & " where timestamp > '" & strDate & " " & "7:00AM" & "'" & _
                " and timestamp <= '" & strDate & " " & "3:00PM" & "'"

else
    SQL = SQL & " where timestamp > '" & strDate & " " & "3:00PM" & "'" & _
                " and timestamp <= '" & strDate & " " & "11:00PM" & "'"
end if

1 个答案:

答案 0 :(得分:1)

我会将讨厌的逻辑排除在SQL字符串之外,并在vbscript中执行。像这样(未经测试):

dim givendate, startdatetime, enddatetime
givendate = cdate(strDate)
startdatetime = CDate(strDate & " " & "3:00PM")
enddatetime = CDate(strDate & " " & "11:00PM")

if strShift="graveyard" then
    if givendate >= cdate("1-6-2019") then
        startdatetime = CDate(strDate & " " & "10:00AM")
        enddatetime = CDate(strDate & " " & "02:00PM")
    else
        startdatetime = DateADD("d", -1, CDate(strDate & " " & "11:00PM"))
        enddatetime = CDate(strDate & " " & "07:00AM")
    end if
end if

if strShift="day" then
    startdatetime = CDate(strDate & " " & "07:00PM")
    enddatetime = CDate(strDate & " " & "03:00PM")
end if

SQL="SELECT timeStamp, coil_number, entry_gaptime,thickness,width_in,grade from entryCoilData" 
SQL = SQL & " WHERE timestamp > '" & startdatetime  & "'"
SQL = SQL & " AND timestamp <= '" & enddatetime  & "'"

response.write(SQL)

通过这种方式,您只需计算startdatetime和enddatetime参数,并对每种情况执行相同的SQL。

请注意,在ASP中编写SQL语句的方式容易受到SQL injection attacks的攻击。<​​/ p>

您可能还想考虑以ISO格式(yyyy-mm-dd)编写日期字符串,这样数据库将始终了解日期。使用cdate("1-6-2019")时,这可能是6月1日或1月6日,这取决于数据库或OS的配置方式。当您使用cdate("2019-6-1")时,这通常被认为是六月初。