Update statement does not update database records - sql

SQL update statement does not update records in database when running the application, but It updates if I run the same Update statement in SQL Server Management studio
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("XXX").ToString())
Dim command As New SqlCommand("Update EmployeeMedicalTest SET [Date tested] = #DateTested, [Next Due date] = #NextDueDate, ECG = #ECG, Lungfunction = #Lungfunction, [Hearing Test] = #HearingTest, [Eye Test] = #EyeTest, [Other Problems] = #OtherProblems, Notes = #Notes WHERE Code = #code", conn)
command.Parameters.AddWithValue("#DateTested", txtDateTested.Text)
command.Parameters.AddWithValue("#NextDueDate", txtNextDueDate.Text)
command.Parameters.AddWithValue("#ECG", txtECG.Text)
command.Parameters.AddWithValue("#Lungfunction", txtLungFunction.Text)
command.Parameters.AddWithValue("#HearingTest", txtHearingTest.Text)
command.Parameters.AddWithValue("#EyeTest", txtEyeTest.Text)
command.Parameters.AddWithValue("#OtherProblems", txtOtherProblems.Text)
command.Parameters.AddWithValue("#Notes", txtNotes.Text)
command.Parameters.AddWithValue("#code", txtClockNo.Text)
conn.Open()
command.ExecuteNonQuery()
lblSaveNotify.Visible = True
conn.Close()

Related

Returning Unique IDs from Oracle Update statement in VB.NET

I am trying to update a selection of rows in an Oracle table we are using to handle messages. Because this table is busy, it would be best if the update could return the UniqueIDs of the rows it updated in an atomic transaction. I modified a code sample I found on StackOverflow to look like the following, but when I examine the parameter "p", I don't find any information coming back from the update statement, as I expected.
Any suggestions for modifying either the .NET code that is setting up the Oracle call, or modifying the Oracle SQL statement itself?
Dim connectString As String = data source=ORA1;user id=MESSAGEBOX;password=MESSAGEBOX
Dim conn As New OracleConnection(connectString)
If conn.State <> ConnectionState.Open Then
conn.Open()
End If
Dim transaction As OracleTransaction = conn.BeginTransaction()
Dim cmd As New OracleCommand()
cmd.Connection = conn
cmd.CommandText = "BEGIN UPDATE MESSAGE_TABLE SET C_WAS_PROCESSED = 2 WHERE C_ID IN (SELECT * FROM(SELECT C_ID FROM MESSAGE_TABLE WHERE C_WAS_PROCESSED = 0 AND C_CREATED_DATE_TIME < CAST(SYSTIMESTAMP AT TIME ZONE 'UTC' AS DATE) ORDER BY C_MESSAGE_PRIORITY, C_ID) WHERE ROWNUM < 16) RETURNING C_ID BULK COLLECT INTO :C_ID; END;"
cmd.CommandType = CommandType.Text
cmd.BindByName = True
cmd.ArrayBindCount = 15
Dim p As New OracleParameter()
p.ParameterName = "C_ID"
p.Direction = ParameterDirection.Output
p.OracleDbType = OracleDbType.Int64
p.Size = 15
p.ArrayBindSize = New Integer() {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}
p.CollectionType = OracleCollectionType.PLSQLAssociativeArray
cmd.Parameters.Add(p)
Dim nRowsAffected As Integer = cmd.ExecuteNonQuery()
transaction.Commit()
conn.Close()
conn.Dispose()
I believe that problem here is that SQL variable being RETURNED BULK COLLECT INTO needs to be of a TABLE type, not a simple number type.
Alter your SQL to include a declaration block like follows:
cmd.CommandText = "DECLARE TYPE IDS IS TABLE OF MESSAGE_TABLE.C_ID%TYPE; C_ID IDS;
BEGIN UPDATE MESSAGE_TABLE SET C_WAS_PROCESSED = 2 WHERE C_ID IN (SELECT * FROM(SELECT C_ID FROM MESSAGE_TABLE WHERE C_WAS_PROCESSED = 0 AND C_CREATED_DATE_TIME < CAST(SYSTIMESTAMP AT TIME ZONE 'UTC' AS DATE) ORDER BY C_MESSAGE_PRIORITY, C_ID) WHERE ROWNUM < 16) RETURNING C_ID BULK COLLECT INTO :C_ID; END;"
I got the table declaration syntax from this oracle-base.com link.

Merge query from datagridview to database not executing sql, vb.net

I'm having a problem executing a merge query from to update or insert values from a DataGridView table into a sql server database table. Here is my code below, it doesn't give me any errors or stoppages, however I recently noticed that it has been creating completely rows in my database table dbo.schedule which contain all NULL values even that key location, could someone please help me? I'm not very familiar with merge queries in sql so please point out issues with my syntax:
Dim query As String = String.Empty
query &= "DECLARE #TaskID nvarchar(8), #Task nvarchar(50), #Start_date datetime, #Due_date datetime, #Complete bit, #Task_Manager nvarchar(8), #JRID nvarchar(10), #Entered_By char(50), #Time_Entered datetime;"
query &= "MERGE INTO schedule USING (VALUES (#TaskID, #Task, #start_date, #Due_Date, #Complete, #Task_Manager, #JRID, #Entered_By, #Time_Entered)) AS t(TaskID, Task, start_date, Due_Date, Complete, Task_Manager, JRID, Entered_By, Time_Entered) "
query &= "ON schedule.TaskID = #TaskID WHEN MATCHED THEN"
query &= " UPDATE SET schedule.TaskID = t.TaskID, schedule.Task=t.Task, schedule.start_date=t.start_date, schedule.due_date=t.due_date, schedule.complete=t.complete, schedule.task_manager=t.task_manager, "
query &= "schedule.JRID=t.JRID, schedule.Entered_by=t.Entered_by, schedule.Time_Entered=t.Time_Entered"
query &= " WHEN NOT MATCHED THEN INSERT (TaskID, Task, start_date, Due_Date, Complete, Task_Manager, JRID, Entered_By, Time_Entered)"
query &= " VALUES (#TaskID, #Task, #start_date, #Due_Date, #Complete, #Task_Manager, #JRID, #Entered_By, #Time_Entered);"
Using conn As New SqlConnection(dbLocations(0, 1))
Using comm As New SqlCommand()
With comm
For Each row As DataGridViewRow In MainSchedule.DataGridView1.Rows
If Not (row.Cells(0).Value = Nothing) Then
.Parameters.Clear()
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
insertcommand.Parameters.AddWithValue("#TaskID", TNn)
insertcommand.Parameters.AddWithValue("#Complete", "False")
insertcommand.Parameters.AddWithValue("#Task", row.Cells(0).Value)
insertcommand.Parameters.AddWithValue("#Start_date", row.Cells(1).Value)
insertcommand.Parameters.AddWithValue("#Due_Date", row.Cells(2).Value)
insertcommand.Parameters.AddWithValue("#JRID", txtJRID.Text)
insertcommand.Parameters.AddWithValue("#Task_Manager", row.Cells(3).Value)
insertcommand.Parameters.AddWithValue("#Entered_By", GetUserName())
insertcommand.Parameters.AddWithValue("#Time_Entered", Now)
NextTask()
End If
Next
End With
conn.Open()
comm.ExecuteNonQuery()
End Using
End Using
I figured it out in case anyone is wondering, here is my new code:
Connexion.Open()
Dim query As String = String.Empty
Dim keypos = 0
query &= "UPDATE schedule SET Task = #Task, Complete = #Complete, Start_date = #Start_date, "
query &= "Due_date = #Due_date, JRID = #JRID, Task_Manager = #Task_Manager, Entered_By = #Entered_By, Time_Entered = #Time_Entered "
query &= "WHERE TaskID = #TaskID "
query &= "IF ##ROWCOUNT = 0 INSERT INTO schedule ( TaskID, Task, start_date, Due_Date, Complete, Task_Manager, JRID, Entered_By, Time_Entered)"
query &= " VALUES ( #TaskID, #Task, #start_date, #Due_Date, #Complete, #Task_Manager, #JRID, #Entered_By, #Time_Entered);"
For Each row As DataGridViewRow In MainSchedule.DataGridView1.Rows
If Not (row.Cells(0).Value = Nothing) Then
insertcommand.Parameters.Clear()
insertcommand.CommandText = query
insertcommand.Parameters.AddWithValue("#TaskID", row.Cells(0).Value)
insertcommand.Parameters.AddWithValue("#Complete", "False")
insertcommand.Parameters.AddWithValue("#Task", row.Cells(1).Value)
insertcommand.Parameters.AddWithValue("#Start_date", row.Cells(2).Value)
insertcommand.Parameters.AddWithValue("#Due_Date", row.Cells(3).Value)
insertcommand.Parameters.AddWithValue("#JRID", txtJRID.Text)
insertcommand.Parameters.AddWithValue("#Task_Manager", row.Cells(4).Value)
insertcommand.Parameters.AddWithValue("#Entered_By", GetUserName())
insertcommand.Parameters.AddWithValue("#Time_Entered", Now)
insertcommand.ExecuteNonQuery()
End If
keypos = keypos + 1
Next
Connexion.Close()

Why is there a syntax error in my update statement in vb.net?

I have been working on my Update Sql statement, but cannot find the syntax error in my code. My insert statement is working, and I am selecting their login Id from another form to compare against.
conn.Open()
Dim SqlUpdate As String = "UPDATE tblLogin SET UserPassword =#UserPassword , FirstName =#FirstName , Surname =#Surname , DateofBirth =#DateofBirth , Phonenumber =#Phonenumber , Emailaddress = #Emailaddress , Administrator = #Administrator , Height = #Height , Weight = #Weight , WHERE UserID = #UserID "
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlUpdate
.Parameters.AddWithValue("#UserPassword", passwordsubmitbox.Text)
.Parameters.AddWithValue("#FirstName", forenamebox.Text)
.Parameters.AddWithValue("#Surname", surnamebox.Text)
.Parameters.AddWithValue("#DateofBirth", DOBselection.Value)
.Parameters.AddWithValue("#Phonenumber", phonenumberbox.Text)
.Parameters.AddWithValue("#Emailaddress", emailadressbox.Text)
.Parameters.AddWithValue("#Administrator", "N")
.Parameters.AddWithValue("#Height", CInt(heightbox.Text))
.Parameters.AddWithValue("#Weight", CInt(weightbox.Text))
.Parameters.AddWithValue("#UserID", Formlogin.UsernameBox1.Text)
.Connection = conn
.ExecuteNonQuery()
End With
conn.Close()
Your query has syntax error remove , after #Weight
Weight = #Weight WHERE UserI ...

Exception from Stored Procedure not caught in .NET using SqlDataAdapter.Fill(DataTable)

I have a Stored Procedure that I am executing from VB.NET. The SP should insert records into a table and return a set to the calling app. The set returned are the records that were inserted.
If the INSERT fails, the exception is caught and re-thrown in the SP, but I never see the exception in my application. The severity level is 14, so I should see it.
Here is the stored procedure:
BEGIN TRY
BEGIN TRANSACTION
-- Declare local variables
DECLARE #DefaultCategoryID AS BIGINT = 1 -- 1 = 'Default Category' (which means no category)
DECLARE #DefaultWeight AS DECIMAL(18,6) = 0
DECLARE #InsertionDate AS DATETIME2(7) = GETDATE()
DECLARE #SendToWebsite AS BIT = 0 -- 0 = 'NO'
DECLARE #MagentoPartTypeID AS BIGINT = 1 -- For now, this is the only part type we are importing from COPICS ('simple' part type)
DECLARE #NotUploaded_PartStatusID AS TINYINT = 0 -- 0 = 'Not Uploaded'
DECLARE #Enabled_PartStatusID AS TINYINT = 1 -- 1 = 'Enabled'
DECLARE #Disabled_PartStatusID AS TINYINT = 2 -- 2 = 'Disabled'
-- Get the part numbers that will be inserted (this set will be returned to calling procedure).
SELECT c.PartNumber
FROM
COPICSPartFile c
LEFT JOIN Part p on c.PartNumber = p.PartNumber
WHERE
p.PartNumber IS NULL
-- Insert new records from COPICSPartFile (records that don't exist - by PartNumber - in Part table)
INSERT INTO Part
([PartNumber]
,[ReplacementPartNumber]
,[ShortDescription]
,[ListPrice]
,[PartStatusTypeID]
,[Weight]
,[CategoryID]
,[DateInserted]
,[SendToWebsite]
,[FileName]
,[MagentoPartTypeID]
,[PrintNumber])
SELECT
c.PartNumber
,c.ReplacementPartNumber
,c.ShortDescription
,c.ListPrice
,CASE WHEN c.PartStatusTypeID = #Enabled_PartStatusID THEN #NotUploaded_PartStatusID ELSE #Disabled_PartStatusID END
,#DefaultWeight
,#DefaultCategoryID
,#InsertionDate
,#SendToWebsite
,#FileName
,#MagentoPartTypeID
,c.PrintNumber
FROM
COPICSPartFile c
LEFT JOIN Part p on c.PartNumber = p.PartNumber
WHERE
p.PartNumber IS NULL
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
ROLLBACK TRANSACTION;
THROW;
END CATCH
And here is the .net code:
Try
'Create command
Dim command As New SqlCommand
command.CommandType = CommandType.StoredProcedure
conn = New SqlConnection(m_ConnectionString)
command.Connection = conn
command.CommandText = "trxInsertPartFromCOPICSPartFile"
With command.Parameters
.AddWithValue("#FileName", fileName)
End With
Dim da As New SqlDataAdapter(command)
Dim dt As New DataTable
da.Fill(dt)
If dt.Rows.Count > 0 Then
Return dt
Else
Return Nothing
End If
Catch ex As SqlException
Dim myMessage As String = ex.Message
Finally
If conn.State <> ConnectionState.Closed Then
conn.Close()
End If
End Try
As I was trying to figure out why the exception (duplicate key) wasn't being caught in my application, I tried commenting out the SELECT statement in the SP just before the INSERT and voila. The exception from the INSERT is caught in the application.
Can someone explain to me why the SELECT statement causes this? I know I can break out the SELECT into another SP, but I'd like to keep it all one atomic transaction if possible. Is this expected behavior? Is there a way around it?
Thanks.
The exception is being swallowed by the Fill method. Instead of using that method, create a SqlDataReader, do a command.ExecuteReader(), and then use the reader to populate the DataTable via Load(). This way the error should occur in the ExecuteReader() method and should be catchable. And then you shouldn't need the SqlDataAdapter.
Try
'Create command
Dim command As New SqlCommand
command.CommandType = CommandType.StoredProcedure
conn = New SqlConnection(m_ConnectionString)
command.Connection = conn
command.CommandText = "trxInsertPartFromCOPICSPartFile"
With command.Parameters
.AddWithValue("#FileName", fileName)
End With
Dim dt As New DataTable
conn.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
dt.Load(reader)
If dt.Rows.Count > 0 Then
Return dt
Else
Return Nothing
End If
Catch ex As SqlException
Dim myMessage As String = ex.Message
Finally
If conn.State <> ConnectionState.Closed Then
conn.Close()
End If
End Try
Also, you might be better off on several levels if you combine the SELECT and the INSERT into a single statement. You can do this via the OUTPUT clause, as follows:
INSERT INTO Part
([PartNumber]
,[ReplacementPartNumber]
,[ShortDescription]
,[ListPrice]
,[PartStatusTypeID]
,[Weight]
,[CategoryID]
,[DateInserted]
,[SendToWebsite]
,[FileName]
,[MagentoPartTypeID]
,[PrintNumber])
OUTPUT INSERTED.[PartNumber] -- return the inserted values to the app code
SELECT
c.PartNumber
,c.ReplacementPartNumber
,c.ShortDescription
,c.ListPrice
,CASE WHEN c.PartStatusTypeID = #Enabled_PartStatusID
THEN #NotUploaded_PartStatusID
ELSE #Disabled_PartStatusID END
,#DefaultWeight
,#DefaultCategoryID
,#InsertionDate
,#SendToWebsite
,#FileName
,#MagentoPartTypeID
,c.PrintNumber
FROM
COPICSPartFile c
LEFT JOIN Part p on c.PartNumber = p.PartNumber
WHERE
p.PartNumber IS NULL

How to write correct grammar of sql query statement in asp.net

now I'm facing a problem: I want to get a total number from result='yes' and 'no' from database.
Actually I try a sql query in my sql server studio is working correctly, but when I place the same sql query in the
code of asps.cs, nothing happens, I don't know why. Hope someone can help me to find the problem.
The code as below:
String query_risk1 = "SELECT (SELECT count(result) FROM [rampDB].[dbo].[Answers] WHERE [result]='yes' AND [company] = #deName1 AND [questionID] BETWEEN '1.1a' AND '1.1e' )+(SELECT count(result) FROM [rampDB].[dbo].[Answers] WHERE [result]='no' AND [company] = #deName1 AND [questionID] BETWEEN '1.1a' AND '1.1e')";
DataSet ds_risk = new DataSet();
SqlDataAdapter riskadapter1 = new SqlDataAdapter(query_risk1, sqlConn);
riskadapter1.SelectCommand.Parameters.Add(new SqlParameter("#deName1", site_name));
DataTable risk_table1 = new DataTable();
riskadapter1.Fill(risk_table1);
ds_risk.Tables.Add(risk_table1);
risk_table1 = ds_risk.Tables[0];
grid2.DataSource = ds_risk;
grid2.DataBind();
Try this query
SELECT SUM(CASE WHEN [result] = 'yes' OR [result] = 'no' THEN 1 ELSE 0 END) As Result
FROM [rampDB].[dbo].[answers]
WHERE [company] = #deName1 AND [questionid] BETWEEN '1.1a' AND '1.1e'
May be something like this
String query_risk1 = "SELECT SUM(CASE WHEN [result] = 'yes' OR [result] = 'no' THEN 1 ELSE END) As Result FROM [rampDB].[dbo].[answers] WHERE [company] = #deName1 AND [questionid] BETWEEN '1.1a' AND '1.1e'";
DataSet ds_risk = new DataSet();
SqlDataAdapter riskadapter1 = new SqlDataAdapter(query_risk1, sqlConn);
riskadapter1.SelectCommand.Parameters.Add(new SqlParameter("#deName1", site_name));
DataTable risk_table1 = new DataTable();
riskadapter1.Fill(risk_table1);
ds_risk.Tables.Add(risk_table1);
risk_table1 = ds_risk.Tables[0];
grid2.DataSource = ds_risk;
grid2.DataBind();
your query is similar to this query:
SELECT count(result)
FROM [rampDB].[dbo].[Answers]
WHERE ([result]='yes' OR [result]='no') AND
[company] = #deName1 AND
[questionID] BETWEEN '1.1a' AND '1.1e'
and finally if you use this query you can tru ExecuteScaler() method to get return value of query:
SqlConnection sqlCon = new SqlConnection("YOUR SQL CONNECTIONSTRING");
SqlCommand sqlCom = new SqlCommand("THE QUERY", sqlCon);
sqlCom.Parameters.AddWithValue("#deName1", "SOME VALUE");
sqlCon.Open();
int count = (int)sqlCom.ExecuteScaler();
sqlCon.Close();