VBA ADODB CommandString Error - sql

So I've got an interesting problem. I'm working with VB modifier (VBA) in Microsoft GP2013, and all I want to do is reference a table in one of our databases, grabbing total amount of call hours based on the service call number (job number) entered. To do so, I have opened an SQL connection, with an SQL command to do so. The problem is, I consistently get conversion errors regardless of how I convert the data coming in, and the data the SQL command is referencing. Here is the error I get:
Conversion failed when converting the varchar value 'Rack build' to data type int.
Here is the command string:
cmdString.CommandText = "SELECT SUM(TRXHRUNT)/100 from CTI_Timetrack_Open_and_Closed where TRXDSCRN = " & CallNumber.Value & ""
Where CallNumber.Value is an integer being populated by our form. I've wrapped my head around this all day, and the answer is probably very simple. I am looking for any advice to alleviate this error. Thanks.

If CallNumber.Value is really an int, then one of your records has a value of 'Rack build' for TRXDSCRN.
Try this select:
SELECT * FROM CTI_Timetrack_Open_and_Closed WHERE TRXDSCRN = 'Rack build';
If there are actually integer values in that column, and you really do want to search for an integer there, you will need to pass it as a string by adding single quotes around CallNumber.Value:
cmdString.CommandText = "SELECT SUM(TRXHRUNT)/100 from CTI_Timetrack_Open_and_Closed where TRXDSCRN = '" & CallNumber.Value & "'"
You really should be using command parameters though to pass the CallNumber.Value in. Otherwise somebody could wreak havoc on your database by passing the following string in for the CallNumber (if it accepts strings):
'; DELETE FROM CTI_Timetrack_Open_and_Closed;--close command with comment
You can use parameters to solve that SQL injection and others using this:
cmdString.CommandText = "SELECT SUM(TRXHRUNT)/100 from CTI_Timetrack_Open_and_Closed where TRXDSCRN = ?";
Dim Pm As ADODB.Parameter
Set Pm = cmdString.CreateParameter("parentid", adNumeric, adParamInput)
Pm.Value = CallNumber.Value
cmdstring.Parameters.Append Pm
I know that TRXHRUNT is not the problem, because if you try to sum on a varchar, you get the following error:
Msg 8117, Level 16, State 1, Line 2
Operand data type varchar is invalid for sum operator.

Related

Retrieving "Number" From Sql VB.NET System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.'

If I want to retrieve a value that is saved as a number in an access database.
Im using the following:
Dim sql As String = "SELECT ArithmeticScore FROM " & tablename & " WHERE DateAscending = '" & todaysdate & "'"
Using connection As New OleDbConnection(getconn)
Using command As New OleDbCommand(sql, connection)
connection.Open()
scorevalue = CDec(command.ExecuteScalar()) 'Data type mismatch in criteria expression.
connection.Close()
End Using
End Using
MsgBox(scorevalue)
getconn = connection string as a string
scorevalue = Nothing as decimal
The field ArithmeticScore is set to Number in the table.
The exact value in the cell right now is 50, but the program should allow for any decimal value.
The error im getting is "Data type mismatch in criteria expression".
The criteria expression mentioned in the error message does not refer to the ArithmeticScore output. It's talking about the WHERE clause. Whatever you have for todaysdate does not match what the database is expecting for the DateAscending column.
Since OleDb is a generic provider, we don't know exactly what kind of database you're talking to, but most databases have a way to get the current date value in SQL: getdate(), current_timestamp, etc. Using that mechanism will likely solve the conflict, and there's no need to use string concatenation for this in the first place.
Dim sql As String = "SELECT ArithmeticScore FROM " & tablename & " WHERE DateAscending = Date()"
The other way you can fix this is with proper parameterized queries, which you should doing anyway. It's NEVER okay to use string concatenation to substitute data into an SQL query, and if you find yourself needing to think about how to format a date or number string for use in an SQL command, you're almost always doing something very wrong.

Input string was not in a correct format Error Filling a Datatable

I have a table which is all VarChar() fields.
I fill the dataset with the following SQL (using vb.net):
Select * From archive_naerns90_2006_q3.NAERNS90_Calls Where siteid = 'NAERNS90-02-627303'
I get this error:
Input string was not in a correct format.Couldn't store <02-627303> in agencyid Column. Expected type is Double.
When I run this query from PgAdmin it works fine. I am running this same bit of code on dozens of other tables with no problems.
The value 02-627303 referenced in the error is the value in the agencyid column for that record, but there are no Double fields in the table. Full disclosure - there were two, but I changed them from Double to VarChar and neither were the agencyid coplumn.
The other kicker is this only happens on some records in that table.
I am guessing I have some corrupt table. I copied the table, but the copy has the same problem. And Since it works in PgAdmin but not from my code it also may have something to do with npgsql.
Edit: I was asked to add the code around the problem area as this looked like an Insert error. I am not doing any Inserts at all in this function.
SQL = "Select * From " & MlocRow("currentdb") & "." & SubTablesArr(Y) & " Where siteid = '" & DataRow("siteid") & "'"
Adapter.SelectCommand = New NpgsqlCommand(SQL, MLConnect)
Adapter.Fill(subDT)
My ConnectionString is:
"HOST=192.168.0.133;DATABASE=masterlists;USER ID=myuser;PASSWORD=mypassword"
Thanks,
Brad
You can type cast that col to varchar() explicitly...

How to convert an string to a Char(20) sql datatype

I am trying to insert a string into a char(20) column in my SQL Server database.
I set the string to be equal to a value and then add it to a parameter
thisstring = "1914"
cmd.Parameters.AddWithValue("#code", thisstring)
However every time I try it ends up looking like this in the database
I need it to look like the 1913, 000000, 000001 ones.
When I try to pad the string with spaces
thisstring= thisstring.PadLeft(20, " ")
or
thisstring = " " & thisstring
I am getting
String or binary data would be truncated
even if the field wasn't 20 characters total
What am I doing wrong?
Edit*** here is the column in SQL Server
http://imgur.com/BbV6VQv
I am not absolutely sure, but I think the problem lies in the AddWithValue.
While convenient this method doesn't allow to specify the exact datatype to pass to the database engine and neither the size of the parameter. It pass always an nvarchar parameter for a C# UNICODE string.
I think you should try with the standard syntax used to build a parameter
Dim p = new SqlParameter("#code", SqlDbType.Char, 20)
p.Value = thisstring.PadLeft(20, " ")
See this very interesting article on MSDN

Date Subtraction within Select Statement

I am currently working on an MS Access database, and am having problem with date subtraction.
Essentially I am trying to create a target date for example:
Target Date = Deadline - Lead Time
i.e. the lead time could be 30 days, therefore the target date should be 30 days prior to the deadline.
The code I am trying to use is this:
strSQL = "INSERT INTO dbo_DEALER_TASK ( Dlr_Number, Action_Id, Task_Id, Area_Id,
Task_Deadline_Date, Responsible_Person_Id, Alternate_Person_Id, Priority, Comment,
Suppress_Email, Dealer_Type ) "
strSQL = strSQL & "SELECT dbo_DEALER_ACTION.Dlr_Number, dbo_DEALER_ACTION.Action_Id,
qryAllTasksToAdd.Task_Id, qryAllTasksToAdd.Area_Id, Deadline_Date - Deadline_adjustment
AS 'Task_Deadline_Date', qryAllTasksToAdd.Person_Responsible_Id,
qryAllTasksToAdd.Alternate_Responsible_Id, qryAllTasksToAdd.Priority,
qryAllTasksToAdd.Comment, qryAllTasksToAdd.Suppress_Email,
qryAllTasksToAdd.Applies_To_Dealer_Type "
strSQL = strSQL & "FROM dbo_DEALER_ACTION LEFT JOIN qryAllTasksToAdd ON
(dbo_DEALER_ACTION.Dealer_Type = qryAllTasksToAdd.Applies_To_Dealer_Type) AND
(dbo_DEALER_ACTION.Action_Id = qryAllTasksToAdd.Action_Id) "
strSQL = strSQL & WHERE (((qryAllTasksToAdd.Task_Id)=" & Me.Task_Id & ") AND
((dbo_DEALER_ACTION.Date_Completed) Is Null));"
DoCmd.RunSQL strSQL
When the VBA code executes the statement, everything is updated correctly, except for the Task_Deadline_Date field, which is being left blank.
What is really confusing me though is if I run this SQL statement standalone it is working as expected. After trying a number of different ideas I tried to replace "Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'" with a string literal date and the statement then worked fine
Does anybody have any ideas what is going wrong?
Thanks,
Chris
You have quoted the alias, you should not do that:
Deadline_Date - Deadline_adjustment AS Task_Deadline_Date
Not
Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'
When you add the quotes, the name of the field is 'Task_Deadline_Date'
Depending on the data type of your date field and whether or not you are using SQL Server, you may need to use DateAdd, for example:
DateAdd("d",-[Deadline_adjustment],[Deadline_Date])
In Access' query designer, start with the version of your query which works and convert it to a parameter query.
WHERE
qryAllTasksToAdd.Task_Id=[which_id]
AND dbo_DEALER_ACTION.Date_Completed Is Null;
You can also add a PARAMETERS statement at the start of the query to inform the db engine about the data type of your parameter. Examples ...
PARAMETERS which_id Text ( 255 );
PARAMETERS which_id Long;
Once you get that query working, save it and give it a name. Then your VBA procedure can use that saved query, feed it the parameter value, and execute it.
Dim db As DAO.database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.QueryDefs("YourQuery")
qdf.Parameters("which_id").value = Me.Task_Id
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
This should be much easier than trying to recreate that SQL statement in VBA code each time you need to execute it.
It sounds like the data type of the column you are inserting in dbo_DEALER_TASK is not actually a datetime field.
I tried to replace "Deadline_Date - Deadline_adjustment AS 'Task_Deadline_Date'" with a string literal date and the statement then worked fine
If you mean '02/20/2012' (as you would correctly use on SQL Server, for example) then this shouldn't work in Access and only will if your output column is a text (= varchar/char)) data type. Date constants in Access are specified like #02/20/2012#
Please confirm the data type of Task_Deadline_Date in your output table.

converting date format in an access table with sql update

I have a problem converting dates while updating an SQL table in VB under access: here is my code:
'Excel format date conversion
strSQL = "UPDATE tblBlotterINTLControl " & _
"SET tblBlotterINTLControl.TradeDate = CVDate(TradeDate), " & _
"tblBlotterINTLControl.SettleDate = CVDate(SettleDate);"
DoCmd.RunSQL strSQL
I obtain an error for each row: "type conversion error"
I have my tables in the right format though, please help thanks
EDIT:
I have to say that a SELECT request works but an UPDATE request doesn't! why? how?
What are the data types of the TradeDate and SettleDate fields in the Access table tblBlotterINTLControl?
SELECT TypeName(TradeDate) AS TypeOfTradeDate, TypeName(SettleDate) AS TypeOfSettleDate
FROM tblBlotterINTLControl;
Please paste that query into SQL View of a new query in Access, run it and show us what you get back.
The reason I asked is because the SET statements in your UPDATE query puzzle me.
SET tblBlotterINTLControl.TradeDate = CVDate(TradeDate)
If the TradeDate field is Date/Time datatype, using the CVDate() function on it doesn't accomplish anything.
If the TradeDate field is text datatype, CVDate() will give you a variant date, but you can't store that Date/Time value back to your text field.
Maybe you would be better off using the Format() function. Here is a sample I copied from the Immediate Window:
? Format("2011/01/01", "d mmm yyyy")
1 Jan 2011
Try CDate instead of CVDate.
CVDate actually returns a Variant of type vbDate and is only around for backwards comparability. Maybe that's what causing the problems.