VB.Net DataAdapter Select String - database

I have a routine to pull data from my database (nothing fancy). I want it to pull rows in which the "StartDate" column is some date in the future. The code below pulls all the rows instead of just the future ones.
I know it must be something silly that I'm doing but I can't figure it out.
Thanks in advance,
Craig
CODE:
Printda = New OleDbDataAdapter("SELECT * FROM tblShows WHERE StartDate > " & Format(Now, "Short Date"), cn)
Updated Code:
Printda = New OleDbDataAdapter("SELECT * FROM tblShows WHERE StartDate > '" & Now.ToString("Short Date") & "'", cn)
Corrected Code:
Printda = New OleDbDataAdapter("SELECT * FROM tblShows WHERE StartDate > Now()", cn)

Try this:
"SELECT * FROM tblShows WHERE StartDate > #" & Now.ToString("MM/dd/yyyy") & "#"
In SQL Server this is the default date format. In Oracle is YYYY-MM-DD. Use the format that fit your needs, or use parameters if you don't want to care about formatting and give your querys security.
Or you could simply use proper function to get the actual date:
"SELECT * FROM tblShows WHERE StartDate > now()"

Related

SQL command to using SUM() with the Where clause

Please I am typing from my phone as I am not with the laptop, don't decrease my reputation.
I have a column in my SQL server database named Total_Amount, I want to get the Sum(Total_Amount) for a specific day for a specific Cashier. I am able to get for specific cashier only but if I want to get using the WHERE clause for both cashier AND date, it returns nothing. The command works well in SQL server Management Studio but from the VB. nET, it does not.
The below is my code.
Dim conn As New SqlConnection("data.
source=PRECIOUSMUM\MSSQLSERVER_1; initial.
catalog=inventory; user id=mantics;
password=emudeji;")
Try
'Dim Total_Amountss As Double
conn.Open()
Dim cmd = New SqlCommand
With cmd
.Connection = conn
.CommandText = "SELECT SUM(Total_Amount)
AS Total_Amount FROM tblOrder WHERE.
(cashier=#cashier) AND (Order_date=#Order_date)"
.Parameters.AddWithValue("#cashier",
lbl_Cashier_Name.Text)
.Parameters.AddWithValue("#Order_date", Date.Today.ToString)
'.Parameters.AddWithValue("#enddate", dtpicker.Value.Date)
End With
Dim dr As SqlDataReader
dr = cmd.ExecuteReader
dr.Read()
If IsDBNull(dr("Total_Amount")) Then
lbl_cashier_Totalsales.Text = "N0.00"
Else
Dim str As Double
str = dr.Item("Total_Amount")
lbl_cashier_Totalsales.Text = FormatCurrency(dr.Item("Total_Amount"))
End If
The first thing that it is clearly wrong is the fact that you use a string to query a Date column. This is never correct because the string is something that you use to display the date to your end users. It is not how the database (or .NET) stores the date value. So, a Date column is not queried using a string but passing directly the C# DateTime value in the Add method and specifying the DataType of the parameter.
A second possible error is caused by the fact that if you have also stored the Time part then passing a Date like Today will never match any row but only the ones that have 00:00:00 as their time value.
You need to query for >= midnight of the starting date and < of the following day.
This considerations will give a query like this:
With cmd
.Connection = conn
.CommandText = "SELECT SUM(Total_Amount) AS Total_Amount
FROM tblOrder
WHERE (cashier=#cashier) AND
(Order_date >= #StartDate AND
Order_date < #EndDate)"
.Parameters.Add("#cashier", SqlDbType.NVarChar).Value = lbl_Cashier_Name.Text
.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = Date.Today
.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = Date.Today.AddDays(1)
End With

Sql Update command VB.Net With Date

I have an SQL update command that I can't get to work. i want it to update the fields where the date is equal to the current date. It works for my INSERT and SELECT statements. But I get a missing operator error when using it for my Delete statement below.
Cmd.Connection = conn
Cmd.CommandText = "UPDATE tbl_Expenditure SET E_Stock =" & NewEStock & "," & "E_Total =" & ETotal & "WHERE [E_Date] = #" & thisMonth & "/" & Day & "/" & thisYear & "#;"
Cmd.ExecuteNonQuery()
Ive tried searching this site as well as others and can't seem to find an answer.
This is my error
Syntax error (missing operator) in query expression '95WHERE [E_Date] = #4/1/2015#'.
Thanks for any help
Using conn As New SqlConnection("connection string here"), _
cmd As New SqlCommand("UPDATE tbl_Expenditure SET E_Stock = #Stock, E_Total = #Total WHERE [E_Date] = #Date;", conn)
'Guessing at column types here
cmd.Parameters.Add("#Stock", SqlDbType.Int).Value = NewEStock
cmd.Parameters.Add("#Total", SqlDbType.Decimal, 8, 2).Value = ETotal
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = New DateTime(thisYear, thisMonth, Day)
cmd.ExecuteNonQuery()
End Using
This fixes a HUGE security issue in the code, it has a performance benefit in allowing Sql Server to cache your query plan, and it solves your problem in that is makes it much easier to spot silly syntax mistakes like the missing space in front of the WHERE clause.

date not being compared in sql server 2000

I have FrmDt and ToDt as datetime column in sql server2000. I am comparing dates in these columns with two datetimepicker like this-
SQL query :
SqlCmd = New SqlCommand("SELECT DISTINCT AllwnsDedId FROM vwGetEmpCntrctWisePaymnt
WHERE Type=1 AND Emp_ID='" & txtEmpID.Text & "'
AND FrmDt>='" & dtp1dtp1.Value.Date & "' AND ToDt<='" & dtp2dtp1.Value.Date & "'", Sqlconn)
In Query Analyzer, I tried :
FrmDt>='01/21/2015' AND ToDt<='01/21/2016'
Its giving me correct output. But I am not getting the output in Vb.net? Anything missing?
In order for this to work reliably you need to use proper Date datatypes. Change your SQL to something like;
WHERE FrmDt>=#FrmDt AND ToDt<=#ToDt
then add 2 paramater objects to the command, one for each date. Your code should end up something like this;
SqlCmd = New SqlCommand("SELECT DISTINCT AllwnsDedId FROM vwGetEmpCntrctWisePaymnt
WHERE Type=1 AND Emp_ID='" & txtEmpID.Text & "'
AND FrmDt>=#FrmDt AND ToDt<=#ToDt", Sqlconn)
SqlCmd.Parameters.Add("#FrmDt", SqlDbType.DateTime).Value = dtp1dtp1.Value.Date
SqlCmd.Parameters.Add("#ToDt", SqlDbType.DateTime).Value = dtp2dtp1.Value.Date

ASP Classic, getting just the data from datetime from a database query

Ive looked around Google and can't find any working code. I want to query my database to return just results from a certain date. But the datetime column in my database has both the Date and the Time.
How would I go about doing this.
today = 15/08/2013
An example of one of the database values = 15/08/2013 02:13:18 PM
And here is my code at the moment
'Connect to database
set conn=Server.CreateObject("ADODB.Connection")
conn.Provider="Microsoft.ACE.OLEDB.12.0"
conn.Open Server.MapPath("/nightclub_photography/data/database/jamsnaps.mdb")
'Get the current date
today = Request.Cookies("sdate")
response.write today
sql = "SELECT * FROM sales WHERE saleDate =" & today
Set rs = conn.Execute(sql)
if rs.EOF then
response.write "Error!"
end if
Dates are passed as strings. Wrap them in single quotes.
sql = "SELECT * FROM sales WHERE saleDate = '" & today & "'"
Hmm, I used this in some other code which seemed to work.
DATEVALUE(columnName)
If you know that today consists of only the date, you could concatenate the time and do something like this:
sql = "SELECT * FROM sales WHERE saleDate >= '" & today & " 00:00:00' AND today <= '" & today & " 23:59:59'"
You could use one of VBScript's date functions to guarantee the contents of today are only the date if you want to be sure. Something like:
today = FormatDateTime(today,vbShortDate)

Search all dates before a specific date in a database (VB.NET|OLE)

I have a database (MDB, Access) and I connect it to my program using an OLE object,
now I have in the db a column filled with dates (ddmmyy),
I want to search and view (in Data grid view) all the fields that has a date before a Specific Date that I define .
the code of search that I used is :
SQLstr = "SELECT * FROM tb WHERE anomber = '" & TextBox1.Text & "'"
What do I have to do?. Thanks.
use the parameters to pass the date to the query, it's more saver(no sql injection) and more perfect(it will convert the date format to the correct format)
SQLstr = "SELECT * FROM tb WHERE anomber < ?"
Command.Parameters.Add(New OleDbParameter("#anomber", TextBox1.Text))
Command.CommandText = SQLstr
Edit:
if the anomber field is the date field so the user can use < instead of =.
the OP question not clear about what he wants.
Edit2:
after executing the command you should assign the results to the grid that you are using to display the data.

Resources