Why is there a syntax error in my update statement in vb.net? - 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 ...

Related

How to get Scalar-value-function result VB.net form through stored procedure

VB.Net Code
' Getting Records Before Transfer to GL
Call OpenAccConnection(lblUserName.Text, lblPassword.Text)
Dim odcTotalsForTransferGL As OleDbCommand = New OleDbCommand("spPet_TotalsForTransferGL", conAccounts)
odcTotalsForTransferGL.CommandType = CommandType.StoredProcedure
' Parameter Assigning
Dim strCompanyCode As OleDbParameter = odcTotalsForTransferGL.Parameters.Add("#ComCod", OleDbType.VarChar, 2)
strCompanyCode.Direction = ParameterDirection.Input
Dim strLocationCode As OleDbParameter = odcTotalsForTransferGL.Parameters.Add("#LocCod", OleDbType.VarChar, 2)
strLocationCode.Direction = ParameterDirection.Input
Dim strPettyCashDate As OleDbParameter = odcTotalsForTransferGL.Parameters.Add("#PetDat", OleDbType.VarChar, 8)
strPettyCashDate.Direction = ParameterDirection.Input
Dim strBegVNo As OleDbParameter = odcTotalsForTransferGL.Parameters.Add("#BegVNo", OleDbType.Integer)
strBegVNo.Direction = ParameterDirection.Output
Dim strEndVNo As OleDbParameter = odcTotalsForTransferGL.Parameters.Add("#EndVNo", OleDbType.Integer)
strEndVNo.Direction = ParameterDirection.Output
Dim strVouTotal As OleDbParameter = odcTotalsForTransferGL.Parameters.Add("#VouTotal", OleDbType.Integer)
strVouTotal.Direction = ParameterDirection.Output
Dim decPetTotal As OleDbParameter = odcTotalsForTransferGL.Parameters.Add("#PetTotal", OleDbType.Decimal)
decPetTotal.Direction = ParameterDirection.Output
Dim intFinancialDates As OleDbParameter = odcTotalsForTransferGL.Parameters.Add("#FinancialDates", OleDbType.Integer)
intFinancialDates.Direction = ParameterDirection.Output
' Passing Parameters
' Company Code
strCompanyCode.Value = cboCompanyCode.SelectedItem.ToString.Substring(0, 2)
' Location Code
strLocationCode.Value = cboLocationCode.SelectedItem.ToString.Substring(0, 2)
' Petty Cash Date(Year & Month)
strPettyCashDate.Value = dtPettyCashDate.Value.Year.ToString + dtPettyCashDate.Value.Month.ToString("D2") + "01"
' Accounts Database Open
conAccounts.Open()
' Stored Procedure Process
Dim odrTotalsForTransferGL As OleDbDataReader = odcTotalsForTransferGL.ExecuteReader()
If odrTotalsForTransferGL.HasRows Then
Do While odrTotalsForTransferGL.Read
lblAccPeriod.Text = odrTotalsForTransferGL.GetValue(4).ToString.Substring(0, 4) + "/" + odrTotalsForTransferGL.GetValue(4).ToString.Substring(5, 4)
lblFiscalMonth.Text = odrTotalsForTransferGL.GetValue(4).ToString.Substring(9, 2)
lblBegVNo.Text = odrTotalsForTransferGL.GetValue(0).ToString
lblEndVNo.Text = odrTotalsForTransferGL.GetValue(1).ToString
lblPettyTotal.Text = odrTotalsForTransferGL.GetValue(3).ToString
Loop
End If
Stored Procedure
ALTER PROCEDURE [dbo].[spPet_TotalsForTransferGL]
-- Add the parameters for the stored procedure here
#ComCod as varchar(2),
#LocCod as varchar(2),
#PetDat as varchar(8),
#BegVNo as int OUT,
#EndVNo as int OUT,
#VouTotal as int OUT,
#PetTotal as decimal(12,2) OUT,
#FinancialDates as varchar(10) OUT
AS
BEGIN
SELECT MIN(PettyDetail.DPetVouNo),
MAX(PettyDetail.DPetVouNo),
MAX(PettyDetail.DPetVouNo) - MIN(PettyDetail.DPetVouNo),
ISNULL(SUM(PettyDetail.DPetAmount), 0)
FROM PettyDetail
WHERE (PettyDetail.DPetComCode = #ComCod) AND
(PettyDetail.DPetLocCode = #LocCod) AND
(YEAR(PettyDetail.DPetDate) = YEAR(CONVERT(Date,#PetDat,111))) AND
(MONTH(PettyDetail.DPetDate) = MONTH(CONVERT(Date,#PetDat,111)))
/* Getting Financial Dates */
EXECUTE #FinancialDates = dbo.fnApp_GetFinancialDates #PetDat
END
Scalar Function
ALTER FUNCTION [dbo].[fnApp_GetFinancialDates]
(
-- Add the parameters for the function here
#PetDat as varchar(8)
)
--RETURNS int(10)
RETURNS varchar(10)
AS
BEGIN
-- Declare the return variable here
--DECLARE #FinancialDates int(10)
DECLARE #FinancialDates varchar(10)
-- Add the T-SQL statements to compute the return value here
IF MONTH(CONVERT(date,#PetDat,111)) BETWEEN 4 AND 12
BEGIN
SELECT #FinancialDates = (SELECT
CAST((YEAR(CONVERT(date,#PetDat,111))) as varchar) +
CAST((YEAR(CONVERT(date,#PetDat,111)) + 1) as varchar) +
REPLICATE('0',(2-(LEN(CAST((MONTH(CONVERT(date,#PetDat,111)) - 3) as varchar))))) + (CAST((MONTH(CONVERT(date,#PetDat,111)) - 3) as varchar)))
END
ELSE
BEGIN
SELECT #FinancialDates = (SELECT
CAST((YEAR(CONVERT(date,#PetDat,111)) - 1)as varchar) +
CAST((YEAR(CONVERT(date,#PetDat,111))) as varchar) +
CAST((MONTH(CONVERT(date,#PetDat,111)) + 9) as varchar))
END
-- Return the result of the function
RETURN #FinancialDates
END
Above function #FinancialDates value didn't return to the .Net form. But other results are return to form.
Can any one please help me to solve this problem. Procedure & Function run correctly in Query Manager.
Two options :
Option 1 : change EXECUTE #FinancialDates = dbo.fnApp_GetFinancialDates #PetDat,
to :
SET #FinancialDates = dbo.fnApp_GetFinancialDates(#PetDat)
Option 2 : Include your fnApp_GetFinancialDates function in your SELECT statement (and you could just remove the #FinancialDates as varchar(10) OUT parameter statement.
ALTER PROCEDURE [dbo].[spPet_TotalsForTransferGL]
-- Add the parameters for the stored procedure here
#ComCod as varchar(2),
#LocCod as varchar(2),
#PetDat as varchar(8)
AS
BEGIN
SELECT MIN(PettyDetail.DPetVouNo) AS 'BegVNo',
MAX(PettyDetail.DPetVouNo) AS 'EndVNo',
MAX(PettyDetail.DPetVouNo) - MIN(PettyDetail.DPetVouNo) AS 'VouTotal',
ISNULL(SUM(PettyDetail.DPetAmount), 0) AS 'PetTotal'
dbo.fnApp_GetFinancialDates (#PetDat) AS 'FinancialDates'
FROM PettyDetail
WHERE (PettyDetail.DPetComCode = #ComCod) AND
(PettyDetail.DPetLocCode = #LocCod) AND
(YEAR(PettyDetail.DPetDate) = YEAR(CONVERT(Date,#PetDat,111))) AND
(MONTH(PettyDetail.DPetDate) = MONTH(CONVERT(Date,#PetDat,111)))
END
and for the option 2 VB code :
If odrTotalsForTransferGL.HasRows Then
Do While odrTotalsForTransferGL.Read
lblAccPeriod.Text = odrTotalsForTransferGL("FinancialDates").ToString.Substring(0, 4) + "/" + odrTotalsForTransferGL("FinancialDates").ToString.Substring(5, 4)
lblFiscalMonth.Text = odrTotalsForTransferGL("FinancialDates").ToString.Substring(9, 2)
lblBegVNo.Text = odrTotalsForTransferGL("BegVNo").ToString
lblEndVNo.Text = odrTotalsForTransferGL("EndVNo").ToString
lblPettyTotal.Text = odrTotalsForTransferGL("PetTotal").ToString
Loop
End If
edited : and don't forget to remove the following code because they are not necessary and will produce errors since the stored proc has no output parameters anymore:
Dim strBegVNo As OleDbParameter =
odcTotalsForTransferGL.Parameters.Add("#BegVNo", OleDbType.Integer)
strBegVNo.Direction = ParameterDirection.Output
Dim strEndVNo As OleDbParameter =
odcTotalsForTransferGL.Parameters.Add("#EndVNo", OleDbType.Integer)
strEndVNo.Direction = ParameterDirection.Output
Dim strVouTotal As OleDbParameter =
odcTotalsForTransferGL.Parameters.Add("#VouTotal", OleDbType.Integer)
strVouTotal.Direction = ParameterDirection.Output
Dim decPetTotal As OleDbParameter =
odcTotalsForTransferGL.Parameters.Add("#PetTotal", OleDbType.Decimal)
decPetTotal.Direction = ParameterDirection.Output
Dim intFinancialDates As OleDbParameter =
odcTotalsForTransferGL.Parameters.Add("#FinancialDates", OleDbType.Integer)
intFinancialDates.Direction = ParameterDirection.Output

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()

How to determine if sql INSERTED or UPDATED?

Say I have a function like this:
Private Function addNicheMerge(ByVal tyNicheMergePOLE As typeNicheMergePOLE) As Integer Implements IGenie.addNicheMerge
Dim objParameterValues As New clsParameterValues
Dim objCon As DbConnection
Dim paramValues() As DbParameter
Dim iConnectionBLL As DataAccessLayer.Connection.iConnectionBLL
iConnectionBLL = New clsConnectionBLL()
Dim intCount As Integer
Try
tyAcornCollision = New typeAcornCollision
objParameterValues = New clsParameterValues
objCon = iConnectionBLL.getDatabaseTypeByDescription("GENIE2")
Using objCon
Dim strSQL As String
strSQL = "If NOT Exists (SELECT * FROM dbNicheMergeLog WHERE MasterID=#MasterID AND ChildID = #ChildID) "
strSQL = strSQL & "INSERT INTO dbNicheMergeLog (MasterID, ChildID, DateAdded, GenieUpdated, done, CheckedByUser, MergeTypeID, Usercode, LastUpdated) VALUES (#MasterID, #ChildID, getDate(), 0, 0, #CheckedByUser, #MergeTypeID, '', " & _ "GetDate()) Else Update dbNicheMergeLog SET LastUpdated = getdate() WHERE MasterID=#MasterID AND ChildID = #ChildID"
objParameterValues.AssignParameterValues("#MasterID", tyNicheMergePOLE.MasterID, 1)
objParameterValues.AssignParameterValues("#ChildID", tyNicheMergePOLE.ChildID, 1)
objParameterValues.AssignParameterValues("#MergeTypeID", tyNicheMergePOLE.MergeTypeID, 1)
objParameterValues.AssignParameterValues("#CheckedByUser", 0, 1)
paramValues = objParameterValues.getParameterValues
intCount = clsDatabaseHelper.ExecuteNonQuery(objCon, CommandType.Text, strSQL, paramValues)
Return intCount
End Using
Catch ex As Exception
Return -2
Finally
' If objCon.State = ConnectionState.Open Then
' objCon.Close()
' End If
objCon = Nothing
End Try
End Function
Is there a way to determine whether an insertion or update took place?
if you are using sql server, you could use an output clause to determine if an update happened
Update dbNicheMergeLog SET LastUpdated =
getdate() WHERE MasterID=#MasterID AND
ChildID = #ChildID
OUTPUT count(*)
Then in vb use
dim updateCount as int = Convert.ToInt32(clsDatabaseHelper.ExecuteScalar())
Try this SQL:
WITH new (
MasterID
,ChildID
,DateAdded
,GenieUpdated
,done
,CheckedByUser
,MergeTypeID
,Usercode
,LastUpdated
)
AS(
SELECT
#MasterID
,#ChildID
,getDate()
,0
,0
,#CheckedByUser
,#MergeTypeID
,''
,getdate()
)
MERGE INTO dbNicheMergeLog t
USING new
ON t.MasterID = new.MasterID
AND t.ChildID = new.ChildID
WHEN NOT MATCHED BY TARGET THEN
INSERT (
MasterID
,ChildID
,DateAdded
,GenieUpdated
,done
,CheckedByUser
,MergeTypeID
,Usercode
,LastUpdated
)
VALUES (
new.MasterID
,new.ChildID
,new.DateAdded
,new.GenieUpdated
,new.done
,new.CheckedByUser
,new.MergeTypeID
,new.Usercode
,new.LastUpdated
)
OUTPUT $action as Action
;
You can use
Output deleted.*
in your update query to get the results that were lost on update, something like this:
Create Table #abctest(
Id int identity,Name varchar(200))
Insert into #abctest(Name)
Values('abcd'),('bcde'),('cdef'),('defg'),('efgh'),('fghi')
Update #abctest Set Name='xyz' OUTPUT Deleted.* Where Id=2
The above query will give you an output
Id Name
2 bcde

existence of particular row in datatable in vb.net windows form

Is it possible to check for existence of a particular row in a datatable?
suppose if there are two rows in datatable, is it possible to check whether the third row exists or not?
For j As Integer = 0 To dtemp.Rows.Count - 1
If dtemp.Rows(j)("empcode").ToString.Trim <> dt.Rows(j)("empcode").ToString.Trim Then
'Insert code
End If
Next
Are you trying to see if your data is existing or not?
Let's say: If you are inserting data in your database, then you can use the textbox property tag to see whether the data is existing or not.
If Me.txtFirstName.Tag = 0 Then
sSQL = "INSERT INTO tblAddressBook ( last_name, first_name, mid_name, birth_date, gender, home_adr, bus_adr, tel_no, mobile_no, email)"
sSQL = sSQL & " VALUES(#last_name, #first_name, #mid_name, #birth_date, #gender, #home_adr, #bus_adr, #tel_no, #mobile_no, #email)"
cmd.CommandText = sSQL
Else
sSQL = "UPDATE tblAddressBook set last_name = #last_name, first_name = #first_name, mid_name = #mid_name, birth_date = #birth_date, gender = #gender"
sSQL = sSQL & " ,home_adr = #home_adr, bus_adr = #bus_adr, tel_no = #tel_no, mobile_no = #mobile_no, email = #email where contact_id = #id"
cmd.CommandText = sSQL
End If
...or else it will update that data in your database. The code above should give you an idea. SINCE you didn't show your code let's talk on this one.
If DataRow.Table.Columns.Contains("column") Then
MsgBox("YAY")
End If

Oledb update sql statement example

con.Open();
cmd = new OleDbCommand("UPDATE staff SET StaffNr = #a, FirstName = #b,
Surname = #c, Email = #d, Balance = #e WHERE Email = #d", con);
cmd.Parameters.AddWithValue("#b", textBoxStaffName.Text);
cmd.Parameters.AddWithValue("#c", textBoxStaffSur.Text);
cmd.Parameters.AddWithValue("#d", textBoxStaffE.Text);
cmd.Parameters.AddWithValue("#e", double.Parse(textBoxSatffBal.Text));
cmd.Parameters.AddWithValue("#a", int.Parse(textBoxStaffNr.Text));
cmd.ExecuteNonQuery();
con.Close();
not updating the database for some reason but the code runs
OldDb uses ? for parameters, not #x. You have to add parameters in order. The name is ignored in AddWithValue (this method comes from a general purpose superclass)
con.Open();
cmd = new OleDbCommand("Update staff set StaffNr = ?, FirstName = ?,
Surname = ?, Balance = ? Where Email = ?", con);
cmd.Parameters.AddWithValue("#a", int.Parse(textBoxStaffNr.Text));
cmd.Parameters.AddWithValue("#b", textBoxStaffName.Text);
cmd.Parameters.AddWithValue("#c", textBoxStaffSur.Text);
cmd.Parameters.AddWithValue("#e", double.Parse(textBoxSatffBal.Text));
cmd.Parameters.AddWithValue("#d", textBoxStaffE.Text);
cmd.ExecuteNonQuery();
con.Close();