2015-09-06 21 views
0

我已將數據庫從Access轉換爲Sql,因爲Sql不接受format()因此顯示錯誤。在預期條件的上下文中指定的非布爾類型的表達式,在'and'附近

這是我的代碼:

DefaultStr = "" & 
"SELECT StudentAccount.Dated, StudentAccountS.StAdmNo, StudentAccountS.StClass, " & 
"StudentAccountS.StName, StudentAccount.Perticular, StudentAccount.Amount,StudentAccount.Remark,StudentAccount.PayMode,TransactionID " & 
"FROM (StudentAccount LEFT OUTER JOIN StudentAccountS ON StudentAccount.SSID = StudentAccountS.SSID) " & 
"WHERE (StudentAccount.Debit) and (StudentAccount.Dated Between " & 
"#" & Format(DateFrom, "MM/dd/yyyy") & "# AND #" & Format(DateTo, "MM/dd/yyyy") & "#)" 


Select Case SIndex 
    Case 0 
     SelStr = " AND (StudentAccount.PayMode = '" & OptionStr & "') Order By StudentAccount.Dated" 
    Case 1 
     SelStr = " AND (StudentAccount.Perticular = '" & OptionStr & "') Order By StudentAccount.Dated" 
    Case 2, 3 
     SelStr = " AND (StudentAccount.TransType = '" & filterStr & "') Order By StudentAccount.Dated" 
    Case Else 
     SelStr = Nothing 
End Select 

Da = New SqlDataAdapter(DefaultStr & SelStr, Conn) 
Ds = New DataSet 
Da.Fill(Ds) 
+1

在'mssql',當你存儲'date'(或'datetime')值不使用''#(像'Access'),但單引號。什麼是DateTo和DateFrom變量?如果他們然後使用這樣的東西:''「&String.Format(」{0:MM/dd/yyyy}「,DateTo)&」'' – nelek

+1

我還會補充說,你不應該使用字符串連接sql命令。使用參數化的sql。看到這個http://stackoverflow.com/questions/306668/are-parameters-really-enough-to-prevent-sql-injections – chrisl08

+0

這也拋出相同的錯誤 – Ankit

回答

0

你必須使用這樣的事情:

Dim CMD As SqlClient.SqlCommand = Conn.CreateCommand 
Dim dtStart As DateTime = New DateTime(2015, 9, 6, 10, 1, 0) 
Dim dtEnd As DateTime = New DateTime(2015, 9, 6, 11, 0, 0) 

CMD.CommandText = "SELECT * FROM Table1 WHERE Date BETWEEN '" & dtStart.ToString("yyyy-MM-dd HH:mm:ss") & "' AND '" & _ 
       dtEnd.ToString("yyyy-MM-dd HH:mm:ss") & "'" 
Dim DA As New SqlClient.SqlDataAdapter 
DA.SelectCommand = CMD 
Dim DT As New DataTable 
DA.Fill(DT) 

Howewer我建議你開始性學習的SqlParameter的查詢(即是更可靠,爲例如在處理SQL注入)。只需使用類似的東西:

CMD.Parameters.Add("@DateStart", SqlDbType.DateTime2, 20).Value = dtStart 
CMD.Parameters.Add("@DateEnd", SqlDbType.DateTime2, 20).Value = dtEnd 
CMD.CommandText = "SELECT * FROM Table1 WHERE Date BETWEEN @DateStart AND @DateEnd" 
相關問題