Trapping Exception using TSQLQuery & params - sql

I am getting a "SQL Server Error: arithmetic exception, numeric overflow, or string truncation" error
here is the code below
AQuery:= TSQLQuery.Create(nil);
with AQuery do
begin
SQLConnection:- AConnection;
SQL.Text:= 'Insert into.....';
ParamByName('...').asString:= 'PCT';
.
.
.
try
ExecSQL;
finally
AQuery.Free;
end;
end;
I have alot of ParamByName lines, and I can't figure out which one is throwing the exception. I just know its thrown on the ExecSQL line. How can i tell which paramByName is causing the error?

When you have the metadata of the table, check the maximum length of string fields. When debugging, check the length of the strings you feed the parambynames. Also check the type of numeric fields, and make sure you don't exceed a maximum value. (I had this problem once with a string which length exceeded the varchars length in the table, and had this problem with a smallint databasefield that I tried to set to a too high value)

Get the SQL text after param substitution and run it as a query in SQL Server management studio.
You'll be able to debug it from there.

You are trying to insert a string value into a field that is not big enough to hold the value. Check the length of the values you are inserting against the length of the field in the table.

As others have said, it's almost certainly that you are pushing too-large a string into one of your fields. It could also happen with numeric values but it's most likely to be a string.
I'd suggest you temporarily alter each of your ParamByName('').AsString:=blah lines with a text constant, eg;
ParamByName('surname').AsString:='Smith';
ParamByName('firstname').AsString:='John';
etc, and see if you get an error. If it goes through without an error, then your problem is most likely to be that one of your string parameters is too long. Check your table schema and debug the actual strings you are putting into the parameters.
Depending on how much access (and experience) you have with this, you might find it more helpful to turn on the SQL Server logging such that you can see your queries (and the contents of those parameters) when the get processed by the SQL server. This will show you exactly what string and numeric values are actually being given to the server.
Which version/edition of SQL Server are you using?

Related

String or binary data of '' would be truncated

I'm trying to resize a column down to 64 characters in length:
ALTER TABLE [dbo].[consumption]
ALTER COLUMN [resourceGroup] VARCHAR(64) NOT NULL
but I get the following error:
String or binary data would be truncated in table 'dbo.consumption', column 'resourceGroup'. Truncated value: ''.
This doesn't make sense to me: how can you truncate nothing?
Any help would be appreciated.
Thanks to comments by #MartinSmith and #DaleK, I think I've come to the answer on this one.
The documentation provided with the data source I'm writing to this column stated that it should not be longer than 64 characters. Then, when I tried changing the length of the column, the error message led me to believe that SQL Server was issuing an error over an empty string. According to #MartinSmith, this type of error message is a recent development and so the offending value probably hasn't been injected into it yet for ALTER TABLE commands. Moreover, queries against the column reveal that it does contain values longer than 64 characters.
Therefore, this error message should be taken at its meaning and the truncation value ignored.

Syntax error in INSERT INTO statement

I am trying to insert some information in an MS Access database.
In my database I have the following columns and types:
log_order - Autonumber (I need this to keep the order where inserted in the db),
userID - Text,
time - Text,
date_ - text,
message - Text.
My query:
command.CommandText = "INSERT INTO logs(userID, time, date_, message) VALUES ('"+verifiedUser+"', '"+msg_time+"', '"+msg_date+"', '"+msg+"')";
OleDbDataReader reader = command.ExecuteReader();
The error that I get:
System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'
I tried several posts but no post helped me. I believe there might be a problem with the autonumber column (log_order). Because of what I remember I don't have to include it in the query.
PS: I know I have to pass the values as parameters.
Thank you in advance
Probably one of your variables (msg?) contains an apostrophe
The way you've written your SQL is a massive security risk. Please immediately look up "parameterized queries" and never, ever, ever write an sql like this again (where you use string concatenation to tack the values into the query). Your code has a proliferation of issues and using parameterized queries will solve all of them; they aren't difficult to write
It seems your data in some of the variables passed in INSERT may be causing this error. Try debugging the value in command.CommandText before executing it.
If any of the variables have a single quote they must be escaped...
Ref: How do I escape a single quote in SQL Server?
Also brush up on SQL Injection Ref: SQL Injection
I totally agree with all that has been said, but to answer your question directly, I am pretty sure you will need to put square brackets around your field names. OleDb tends not to like special characters and could well be having a problem for example with date_ ; sending [date_] instead should get round the issue.
It will not like time either. Same solution
Addendum on SQL Injection
As an aside, in fact calling Access through OleDb is relatively protected from SQL Injection. This is because any attempt to execute multiple instructions in one command fails. (You get an incorrect formatted string error). So whilst you could argue that what you are doing is safe, it is not for other db providers. The sooner you get into good habits, the less likely you will be to introduce a vulnerability in a case where it could be dangerous. If it seems like you are getting a stream of abuse, it is just because everyone here wants to keep the net safe.

Getting an SQL Exception about being unable to convert one data type to another, but only when a field is too long?

I have a massive stored procedure that I did not write. It's about 10K lines long. Part of it creates a few temp tables, inserts some records into these tables, then goes through about 8,000 lines of validation and removes invalid records from the tables and re-inserts them into a temp Error table for reporting back to the user.
Somewhere along the lines, I get the following SqlException in my C# code:
Conversion failed when converting the varchar value 'AAAAAAAABA683' to data type int.
But if I shorten the value down to just A683 or something, the procedure runs as expected and just marks this particular record as an error. So it sounds to me like it's not actually a problem with the data types, but something else.
Unfortunately the LineNumber property of the SqlException I catch doesn't help me, since I don't have access to seeing the actual SQL being executed. I can only look at the procedure itself.
Has anyone encountered something like this before?
When I get this error, it is because I am using + as a string concatenation operator, but one (or more) of the arguments is an integer. By the rules that SQL Server uses, if any argument is an integer, then the + is treated as addition rather than string concatenation.
Unfortunately, with a 10,000-line stored procedure you have few options (there could be a diatribe here about software engineering, making code more modular, and using constraints to validate data, but that would not be helpful).
What can you do? I don't actually know. You have a bug in your code, in the sense that the stored procedure is not expecting the types of values you are providing (and all the more ironic because it sounds like most of the procedure is validating values). Some logic in the stored procedure is changing the shorter value to something acceptable for numeric conversion, perhaps something like substring(val, 2, 5) and expecting the value to be an integer.
You could prevent the error by using the concat() function for string concatenation in the stored procedure rather than +. However, that might just hide some other error in the code. You could also prevent the error by pre-validating the data and preventing certain rows from being passed in.

Error while Querying : The value of a host variable in the EXECUTE or OPEN statement is too large for its corresponding use

On trying to use a select query statement. The input variable has 8 characters just as expected.
I dont know why this error comes for select query because for a select query it will query and if its available it will return else it will retun blank rows.
Hibernate is used. Even in mapping its correctly mapped as 8 only.
This is what i found in log file:
Cause = com.ibm.db2.jcc.a.SqlException: The value of a host variable in the EXECUTE or OPEN statement is too large for its corresponding use.
Has anybody come across this error before? Please suggest me some solutions on why this error occurs..
One possibility... This issue can come even in SELECT statement. When the parameter passed into the query is more than the size of its datatype's size, this error will pop-up.
Example:
Datatype - CHAR(12)
Search Param: "123456789012345"

Issues with Chr(0) in SQL INSERT script

We currently use the SQL Publishing Wizard to back up our database schemas and data, however we have some database tables with hashed passwords that contain the null character (chr(0)). When SQL Publishing Wizard generates the insert data scripts, the null character causes errors when we try and run the resulting SQL - it appears to ignore ALL TEXT after the first instance of this character in a script. We recently tried out RedGate SQL Compare, and found that it has the same issue with this character. I have confirmed it is ascii character code 0 by running the ascii() sql function against the offending record.
A sample of the error we are getting is:
Unclosed quotation mark after the character string '??`????{??0???
The fun part is, I can't really paste a sample Insert statement because of course everything that appears after the CHR(0) is being omitted when pasting!
Change the definition of the column to VARBINARY. The data you store in there doesn't seem to be an appropiate VARCHAR to start with.
This will ripple through the code that uses the column as you'll get a byte[] CLR tpe back in the client, and you should change your insert/update code accordingly. But after all, a passowrd hash is a byte[], not a string.