Short Date from text field into sql statement ms access - sql

strSQLzm1a = "INSERT INTO dbGrafikTest (imieNazwisko, numerTelefonu, zmiana, praca, data) VALUES ('" & Me!listZM1a.Column(0) & "', '" & Me!listZM1a.Column(1) & "', 'zm1', 'automatyk', #" & Me!txtData & "#);"
This SQL statement returns error:
Syntax error in date in query expression '#21.03.2016'.
txtData is a text field and its formated as Short Date.
I'm searching googles to find the answer for where i made a syntax error and i really dont understand where i did it.
Database column data is formated as Date/Time as well.

The db engine can't cope with 21.03.2016 as a date literal.
Format it in a way which the db engine can use.
Change this ...
& Me!txtData &
to this ...
& Format(Me!txtData, "yyyy-m-d") &
Or you could use a parameter query, and then supply the needed Date/Time value without format concerns.

Related

Problem using where with date in SQL Statement

I am trying to execute an SQL statement in a VBA script. I have gotten the script to run, but it ignores the where with a date filter.
I have researched and tried every option I can find, but just cant seem to get it to work.
Set rs = conn.Execute("Select [adjustment_number], [status], [tax_adjusted],[amount], [gl_date],[creation_date],[apply_date],[comments],[type],[adjustment_type],[dbo].[Code_Combinations].[segment1], [dbo].[Code_Combinations].[segment10],[dbo].[Code_Combinations].[segment11],[dbo].[Code_Combinations].[segment12],[dbo].[Code_Combinations].[code_combination] FROM [dbo].[AR_ADJUSTMENTS_ALL] " & _
"left outer join [dbo].[Code_Combinations] on [dbo].[AR_ADJUSTMENTS_ALL].[CODE_COMBINATION_ID] = [dbo].[Code_Combinations].[CODE_COMBINATION_ID] where [gl_date] >= " & gldate & ";")
(Copying this from my comment above, into an answer, since this solved your problem)
SQL Server? Put single quotes around your date in the WHERE clause.
where [gl_date] >= '" & gldate & "';"
Assumes that gldate is a valid date, and [gl_date] is of a date datatype.

Why doesn't this WHERE clause return the right datums?

I'm trying to query a .mdb database, and this is part of the SQL in VB.Net:
sql = sql + "WHERE datdatum BETWEEN #" & "15-10-2018" & "# And #" & "31-10-2018" & "#"
The where clause is working the way you assume. At the moment I change the first date from 15-10-2018 to 01-10-2018, it shows all records from Jan-10 instead of Oct-01.
There are two problems here.
First, don't format the dates that way. Dates used for SQL should always use the ISO8601 format. For date-only values with no time component, there are some reasons to prefer the lesser-known unseparated variant of the standard format, but that's still ISO8601. So the date values should look like this:
sql = sql + "WHERE datdatum BETWEEN #" & "20181015" & "# And #" & "20181031" & "#"
or this:
sql = sql + "WHERE datdatum BETWEEN #" & "2018-10-15" & "# And #" & "2018-10-31" & "#"
Anything else is just begging for the kind of problem in your question, where the actual date read from the string varies based on the culture of the person/device making the interpretation.
This fix might seem to work on it's own, but we still need to do more work because of the 2nd issue:
DON'T USE STRING CONCATENATION TO PUT DATA INTO AN SQL QUERY!
You should always build the query more like this:
sql = sql + " WHERE datdatum BETWEEN ? And ?"
Concatenation is okay, as long as no data, such as a date value, is used. Then you populate the values like this (assuming you have an OleDbCommand object named cmd):
cmd.Parameters.Add("?", OleDbType.Date).Value = DateTime.Parse("2018-10-15")
cmd.Parameters.Add("?", OleDbType.Date).Value = DateTime.Parse("2018-10-31")
This completely avoids the formatting issue from the question, because you're working with .Net DateTime values. It can sometimes run faster (though it may not matter for Access). And it protects against SQL injection issues, both malicious and benign. IMO anything else is amateurish and borders on professional malpractice.

Insert data to a SQL Server database that contains apostrophes

I'm making this program on Vb.net 2012 that has a connection to SQL Server 2012.
One of the columns of this database table is Description, and in some cases the date may include apostrophes, for example... 'chainsaw 15'3" X 1 1/2 X .050 X 3/4'
When I run the query the apostrophe that is between the data causes an error at the syntax of the query, this is the query line in VB.net.
CMD.CommandText =
"INSERT INTO Table_ARTICLES
(NUMPART, DESCRIPTION, LOCATION, MAX, ACTUAL, MIN, Unidad_de_medida)
VALUES ('" & txtNumParte.Text & "', '" & txtDescripcion.Text & "',
'" & txtLocaclizacion.Text & "', '" & txtMaximo.Text & "', '" & txtActual.Text & "',
'" & txtMin.Text & "', '" & cmbUnidad.Text & "')"
Does anybody know how to make this query accept those characters on the query?
As #pmbAustin pointed out, is a terrible idea to build sql statements via string concatenation due to SQL Injection attacks and other problems. The approach you should use is called a parametrized query:
CMD.CommandText = "INSERT INTO (NUMPART, DESCRIPTION, LOCATION, MAX, ACTUAL,
MIN, Unidad_de_medida)
VALUES (#NUMPART, #DESCRIPTION,#LOCATION,#MAX,#ACTUAL,#MIN,#UNIDAD_DE_MEDIDA)"
And then:
CMD.Parameters.Add("#NUMPART",txtNumParte.Text);
CMD.Parameters.Add("#DESCRIPTION",txtDescripcion.Text);
//...and so on
CMD.ExecuteNonQuery();
Please use parameterized SQL (i.e. stored procedures) to prevent SQL injection and the like.
As for your question, you would want to replace the single quote (apostrophe) with two single quotes before you add it as a parameter. This way the first one acts as an escape character which will allow for the apostrophe to be inserted into the database.
Example:
txtNumParte.Text.Replace("'", "''")

SQL Filter doesn't work with past year

I got a very strange problem.
When I filter my data in the current year everything is working fine:
But If I try to go back a year, suddenly I get a blank report...
Going to the next year isn't a problem, like you can see here:
My code is:
These 2 values come through as a 'date' in a private sub
datumvan = DateTimePickerVan.Value.ToLocalTime
datumtot = DateTimePickerTot.Value.ToLocalTime
Dim culture As New CultureInfo("pt-BR")
sqlstr = "SELECT * FROM [Geschiedenis$] WHERE Aangemeld BETWEEN '" & datumvan.ToString("d", culture) & "' AND '" & datumtot.ToString("d", culture) & "'"
See also how the sql looks like if it goes to the debugging:
So to conclude: everything is working fine unless I go to the previous year.
If I place: NOT BETWEEN, everything is reversed, and I see all the data.
I tried to replace BETWEEN with >= and <= as well, but the same thing occurred.
Any ideas?
Aangemeld is obviously a date, as it should be. So you must compare Aangemeld with dates. In order to do so,
first convert the dates to strings in VB. Make this a specific date format, rather than relying on some region settings. E.g. datumvan.ToString("dd/MM/yyyy")
then convert the string to date in SQL. Again don't rely on database settings, but name the format you are using.
How to convert a string to a date in SQL depends on the DBMS you are using. Here are some examples:
MySQL:
" ... WHERE Aangemeld BETWEEN STR_TO_DATE('" & datumvan.ToString("dd/MM/yyyy") & "','%d/%m/%Y') AND ... "
SQL_Server:
" ... WHERE Aangemeld BETWEEN CONVERT(datetime,'" & datumvan.ToString("dd/MM/yyyy") & "',103) AND ... "
Oracle:
" ... WHERE Aangemeld BETWEEN TO_DATE('" & datumvan.ToString("dd/MM/yyyy") & "','dd/mm/yyyy') AND ... "
Many DBMS (such as MySQL, SQL-Server, and PostgreSQL) also accept a string in ISO format as as date literal.
" ... WHERE Aangemeld BETWEEN '" & datumvan.ToString("yyyyMMdd") & "' AND ... "
In Oracle such a literal must be preceded by DATE:
" ... WHERE Aangemeld BETWEEN DATE'" & datumvan.ToString("yyyyMMdd") & "' AND ... "
One more thing: I don't know if this is the case in other DBMS, too, but I know that Oracle treats a date without time as a date at midnight, as it only knows datetime data type. So a between clause would exclude the last day. Which is why in Oracle you would compare TRUNC(Aangemeld) instead of Aangemeld.

Updating a field dependent on a date range in Access with VisualBasic and SQL

A friend and I have been trying for hours with little progress to a get a piece of code right for an invoicing system we're designing as a project.
We are trying to update the field InvoiceNo to a value (worked out earlier in the VisualBasic code), where the CustomerNo is the is a specific value and the FinishDate is between two dates. At first I was trying to use TO_DATE but then we realized that wasn't the same in the SQL that Access uses (after much searching).
This has been the simple statement I've been using to just test and try to get something working to then translate into VisualBasic and put in our variables. It's a little easier to read so I thought I'd provide it.
UPDATE tblJob SET tblJob.InvoiceNo = '8' WHERE tblJob.CustomerNo = '1' AND (tblJob.FinishDate BETWEEN cdate(format('08/09/2013', '##/##/####')) AND cdate(format('03/10/2013', '##/##/####')));
I have a feeling after looking at a few examples that our date is meant to be without an forward slashes. So I tried that and it wasn't working either.
Here's the VisualBasic code that has come out of all of this, it's exactly the same but using some variables rather than our set values that I've been using for testing.
DoCmd.RunSQL ("UPDATE tblJob SET tblJob.InvoiceNo = '" & newInvoiceNo & "' WHERE tblJob.CustomerNo = '" & VbCustNo & "' AND (tblJob.FinishDate BETWEEN cdate(format('" & Forms![frmMainMenu][txtFirstDate] & "', '##/##/####')) AND cdate(format('" & Forms![frmMainmenu][txtEndDate] & "', '##/##/####')));")
We had a look at: Convert a string to a date in Access and it helped us realize that it was cdate(format()) rather than TO_DATE as it is in Oracle. But we just can't seem to get it to run properly, any help would be much appreciated.
If you will be running the query from within an Access application session, you can let the db engine use the Access expression service to grab the values from the text boxes on your form.
Dim db As DAO.Database
Dim strUpdate As String
strUpdate = "UPDATE tblJob" & vbCrLf & _
"SET InvoiceNo = '" & newInvoiceNo & "'" & vbCrLf & _
"WHERE CustomerNo = '" & VbCustNo & "'" & vbCrLf & _
"AND FinishDate BETWEEN Forms!frmMainMenu!txtFirstDate AND Forms!frmMainmenu!txtEndDate;"
Debug.Print strUpdate
Set db = CurrentDb
db.Execute strUpdate, dbFailOnError
Set db = Nothing
However, if you prefer to build the literal date values from those text boxes into your UPDATE statement, you can use Format().
"AND FinishDate BETWEEN " & _
Format(Forms!frmMainmenu!txtFirstDate, "\#yyyy-m-d\#") & _
" AND " & Format(Forms!frmMainmenu!txtEndDate, "\#yyyy-m-d\#") & ";"
Either way, using a string variable to hold your UPDATE statement gives you an opportunity to examine the completed statement you're asking the db engine to execute.
You can view the output from Debug.Print in the Immediate window (go there with Ctl+g). For troubleshooting, you can copy the statement text from there and then paste it into SQL View of a new Access query.