Unhandled Exception Error inserting record into SQL Database using VB - sql-server

My code is causing this error when trying add a record in the database:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near ','
The error is pointing to this line in my code. I am selecting a date using MonthCalendar1.SelectionRange.Start.ToShortDateString and inserting it into my database.
I thought it had to do with the date format, so I changed the date column format on my tables in the database from date to string and it not help. Also tried different formats for the date format was different to that from my client - made them the same to no avail.
This SQL is working.
INSERT INTO Event_Booking (Client_ID, Event_Name, Event_Status, No_of_People, Booking_Location, Event_Time_ID, Booking_Date)
VALUES (#Client_ID, #Event_Name, #Event_Status, #No_of_People, #Booking_Location, #Event_Time_ID, #Booking_Date);
SELECT
(Event_ID, Client_ID, Event_Name, Event_Status, No_of_People, ,
Booking_Location, Event_Time_ID, Booking_Date)
FROM
Event_Booking
WHERE
(Event_ID = SCOPE_IDENTITY())
This code is not working with the error at the line marked **
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
***Insert A New Booking
Event_BookingTableAdapter.InsertNewBooking(TextBox5.Text, TextBox20.Text, TextBox21.Text, TextBox6.Text, TextBox4.Text, TimeSlotComboBox.SelectedValue, MonthCalendar1.SelectionRange.Start.ToShortDateString)***
End Sub

Related

How to execute dynamic SQL in .net?

I'm trying to write the SQL execute statement below. I'm getting an error in .net saying
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Invalid column name 'Survey'
There is no Survey column which is correct, but what is crazy is that it is getting that value from the #SurveyNumber variable. I think my exec code is correct, but maybe I'm not escaping the #SurveyNumber properly?
The #SurveyNumber variable contains this string "Survey - 1234"
#SurveyNumber varchar(50),
#RefIds varchar(max)
AS
Begin
exec('SELECT
Distinct
r.DRAWING,
r.[DESC],
r.REFMEMO,
r.OP_PSI,
r.MAX_PSI,
r.MAX_TEMP,
r.DESIGN,
r.CORR_RATE,
r.MIN_INSP,
r.INSP_LOC,
r.REPL_DATE,
r.LAST_INSP,
r.NEXT_INSP,
r.ALLOW_PSI,
IIf( r.[CF1] is null Or r.[CF1]='''',''Max'', IIf(r.[CF1]=''L'',''Long'',IIf(r.[CF1]=''S'',''Short'',IIf(r.[CF1]=''U'',''User'',''NA''))))AS CF1,
r.[NF2]*1000 as NF2,
r.CF2,
r.V_Last_Insp,
r.V_Next_Insp,
r.V_Concern,
r.V_Memo,
r.V_Report,
r.V_Interval,
r.Insulated,
r.AVG_NEXT_INSP,
r.AVG_REPL_DATE,
r.Scaffolding,
r.Number_Xrays,
r.MIN_RMS,
r.DRAWING_FLAG
From ref r
where r.SurveyNumber = ('+#SurveyNumber+') and r.Id In ('+#RefIds+')
ORDER BY r.NEXT_INSP asc')
End

How to log the failed records while insert the data in bulk mode

I am inserting the data in bulk mode.I want to insert the data from one db table to another db table. I am using Scatter-gather message processor.I have 10 records in source db table, in this 10 records the second record has some invalid data (like firstname is null) remaining 9 records are valid data, but in my target db table firstname column is not null. While inserting these 10 records into target db, its throwing the error as firstname is not null. How to identify particular record has invalid data using exception handling in mule. I am new in mule esb. Can anyone help on this scenario.`
%output application/java
payload map
{
id : $.Id,
customerid : $.Customerid,
address : $.Address,
dob : $.Dob,
firstname : $.Firstname,
lastname : $.LastName,
middlename : $.Middlename,
phoneno : $.Phoneno,
batch : $.Batch,
recorddate : $.RecordDate
}]]>
`
Kindly post the exception message you are getting along with your xml flow.
But as of now i may give below suggestion.
Use a collection splitter to split and process each records.
catch the exception in the error handling block using the context #**[Exception.causedBy(your exception class)]**
After this kindly configure your strategy what to do in case of this exception happens.
In your case log your information with any column value or any record id that is unique for every message.This may help you out to see on which particular record your exception has occurred.
Thanks!

Dynamics AX 2012: Conversion failed when converting date and/or time from character string

In AX I have several entities. When I try to post unposted timesheets it works fine for all entities except of one where I'm getting SQL error: "Conversion failed when converting date and/or time from character string"
The call stack is below:
In highlighted method I see that it cannot find any SourceDocumentHeader in AccountDistribution table, so the AccountingDate is empty.
Has anybody experienced same problem and knows how to solve it?
It is strange for me because all other entities works OK.
Thanks.
The technical explanation of what you are seeing is that this part of the code generates invalid SQL, but it looks to me as if you have a problem with your setup.
If you run date2str on an empty date it returns an empty string. Please try this in a job and you will see an empty string in the infolog.
static void TestEmptyDate(Args _args)
{
AccountingDate _date;
;
info(date2str(_date, 321, 2, 3, 2, 3, 4, DateFlags::None));
}
That then gets concatenated in the method updateDistributionsForEvent to generate an SQL statement:
sqlStatementText = strFmt('UPDATE T1 SET ACCOUNTINGEVENT=%1,RECVERSION=%2 FROM ACCOUNTINGDISTRIBUTION T1 WITH (INDEX(I_7452SOURCEDOCUMENTHEADERIDX)) CROSS JOIN SOURCEDOCUMENTLINE T2 ', _accountingEventRecId, xGlobal::randomPositiveInt32());
sqlStatementText += strFmt('WHERE (((T1.PARTITION=%1) AND (T1.ACCOUNTINGEVENT=0) AND (T1.ACCOUNTINGDATE={ d\'%2\'})) AND (T1.SOURCEDOCUMENTHEADER=%3)) AND ', getcurrentpartitionrecid(), sqlDate, _sourceDocumentRecId);
sqlStatementText += strFmt('((T2.RECID=T1.SOURCEDOCUMENTLINE) AND (T2.ACCOUNTINGSTATUS=%1 OR T2.ACCOUNTINGSTATUS=%2)) AND (T2.PARTITION=%3)', enum2int(SourceDocumentLineAccountingStatus::Completed), enum2int(SourceDocumentLineAccountingStatus::Canceled), getcurrentpartitionrecid());
Where T1.ACCOUNTINGDATE={ d\'%2\'} is the relevant part which generates T1.ACCOUNTINGDATE={ d''} in the SQL string.
If you try running
select {d''}
in SQL you will get
Msg 241, Level 16, State 3, Line 1 Conversion failed when converting
date and/or time from character string.
because an empty string cannot be parsed to a date.

Sql Server: getting the names of the objects involved in errors [duplicate]

How do I correctly extract specific info from an sql error message number 547?
Info Required:
Table Name
Constraint Name
Column Name
Code:
Try
....
Catch ex As System.Data.SqlClient.SqlException
If ex.Number = 547 Then
End If
End Try
Sample message:
UPDATE statement conflicted with COLUMN CHECK constraint
'CK_Birthdate'. The conflict occurred in database 'Northwind', table
'Employees', column 'BirthDate'.
There is no straight forward way of getting these pieces of information separately.
It all gets concatenated into the error message.
You can use select * from sys.messages where message_id=547 to see the various different language formats of the message that you would need to deal with in order to extract the constituent parts then perhaps use regular expressions with capturing groups based around this information.
In addition to queries, here's a powershell script which wraps the sys.messages queries.
http://blogs.msdn.com/b/buckwoody/archive/2009/04/30/and-the-winner-is-get-sql-server-error-messages-from-powershell.aspx
its true there is no straight way to fix this but I did this insted
var str = sqlException.Message.ToString();
var strlist = str.Split(',', StringSplitOptions.RemoveEmptyEntries);
var streplace = strlist[1];
streplace = streplace.Replace("table \"dbo.", "");
streplace = streplace.Replace("\"", ""); //this will get the data table name
streplace = string.Concat(streplace.Select(x => Char.IsUpper(x) ? " " + x : x.ToString())).TrimStart(' ');

Getting "Multiple-step operation generated errors. Check each status value." error using ADO with SQL server 2008

We are in the process to migrate our SQL 2000 box to SQL 2008. But we ran into an issue; when a result set (rows or not) is returned by using a query that has a UNION. Later in the code we try to add a new row and assign field to it but because a UNION was used, when we try to assign a value to the field it gives us a Multiple-step operation generated errors. Check each status value. error. We tried the following code on a Windows XP & Windows 7 and got the same result. But when we change our connection string to point back to our SQL 2000 box we don't get that error any more.
The following example show the problem we are having.
var c = new ADODB.Connection();
var cmd = new ADODB.Command();
var rs = new ADODB.Recordset();
object recordsAffected;
c.Open("Provider=SQLOLEDB;Server=*****;Database=*****;User Id=*****;Password=*****;");
cmd.ActiveConnection = c;
cmd.CommandType = ADODB.CommandTypeEnum.adCmdText;
cmd.CommandText = "create table testing2008 (id int)";
cmd.Execute(out recordsAffected);
try {
cmd.CommandText = "select * from testing2008 union select * from testing2008";
rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient;
rs.Open(cmd, Type.Missing, ADODB.CursorTypeEnum.adOpenDynamic, ADODB.LockTypeEnum.adLockBatchOptimistic, -1);
rs.AddNew();
rs.Fields["id"].Value = 0; //throws exception
rs.Save();
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
finally {
cmd.CommandText = "drop table testing2008";
cmd.Execute(out recordsAffected);
c.Close();
}
The link below is an article that gives a great breakdown of the 6 scenarios this error message can occur:
Scenario 1 - Error occurs when trying to insert data into a database
Scenario 2 - Error occurs when trying to open an ADO connection
Scenario 3 - Error occurs inserting data into Access, where a fieldname has a space
Scenario 4 - Error occurs inserting data into Access, when using adLockBatchOptimistic
Scenario 5 - Error occurs inserting data into Access, when using Jet.OLEDB.3.51 or ODBC driver (not Jet.OLEDB.4.0)
Scenario 6 - Error occurs when using a Command object and Parameters
http://www.adopenstatic.com/faq/80040e21.asp
Hope it may help others that may be facing the same issue.
It is type mismatch, try
rs.Fields["id"].Value = "0";
or make sure you assign a Variant to the value.
Since I posted this problem, we figured out that the problem was when you do a union the attributes on the fields are not bound (i.e. the attributes: basecatalog, basetable & basecolumn are empty) to remedy our problem we had to force the values of those attributes, by saving the recordset to xml (adPersistXML), change the xml and reopen the recordset from the xml. This rebound the fields and we were able to continue. We know this may not be the most efficient solution, but it was for an older app and we didn't want to rewrite the sql statements. It looks like the main error Multiple-step operation generated errors. Check each status value. is related to when an error occurs when a value is assigned to a field.
Two things I can think of... Make sure your "ID" column will accept a zero (0). Also - I've stopped this issue on one occasion by not using the adUseClient cursor (try server).
Many times this is a type mismatch, trying to stuff a NULL into a non-null column, or attempting to write more characters into a column than it's designed to take.
Hope this helps. - Freddo
Same issue occurred to me the problem was that i violated an object property , in my case it was size the error came out as
"IntegrationException: Problem (Multiple-step operation generated errors. Check each status value.)"
Imports ADODB
Dim _RecordSet As Recordset
_rs.Fields.Append("Field_Name", DataTypeEnum.adVarChar, 50)
_Recordset("Field_Name").Value = _RecordDetails.Field_NameValue
_RecordDetails.Field_NameValue length was more than 50 chars , so this property was violated , hence the error occurred .
I found another scenario:
When I was trying to set the value of a adLongVarChar field in a new record for a memory-only adodb.recordset. In my case, the error was triggered because the string I was passing had a buried unicode character.
I found this error when our legacy application was trying to parse 1/1/0001 12AM date and time. Looks like VB6 recordsets doesn't like that value.
To get rid of the errors, I had to set all the offending dates to null.
I was getting this error when trying to insert/update the field with a value that did not match the table>field type.
For example, the database table > field was
char(1)
however, I was trying to insert/update
"apple"
into the record.
Once I change the inputted value to "a" and it worked.

Resources