Must declare the scalar variable "#Modifier" - sql

I have been trying to figure out what I am doing wrong for a few hours now. I am trying to add a record to my database but I am not able to do so because of the error I am getting that reads "Must declare the scalar variable "#Modifier"." I noticed other people with similar issues but I couldn't apply the same fixes to my code.
Dim dbConnection As SqlConnection = connectToDb()
Dim sqlString As String
If currentWeapon.Id > 0 Then
sqlString = "Update Weapons Set Name = #name"
Else
sqlString = "INSERT INTO Weapons (Name, APPower, HEPower, Range, Modifier) VALUES(#name, #APPower, #HEPower, #Range, #Modifier)"
lastWeaponId += 1
currentWeapon.Id = lastWeaponId
End If
Dim com As New SqlCommand(sqlString, dbConnection)
com.Parameters.Add("#name", SqlDbType.VarChar).Value = currentWeapon.Name
com.Parameters.Add("#APPower", SqlDbType.Int).Value = currentWeapon.APPower
com.Parameters.Add("#HEPower", SqlDbType.Int).Value = currentWeapon.HEPower
com.Parameters.Add("#Range", SqlDbType.Int).Value = currentWeapon.Range
com.Parameters.Add("#Modifer", SqlDbType.VarChar).Value = currentWeapon.Modifier
Try
Dim result = com.ExecuteNonQuery()
MessageBox.Show(result.ToString)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

You wrote #Modifer instead of #Modifier
com.Parameters.Add("#Modifer", SqlDbType.VarChar).Value = currentWeapon.Modifier
^

You have a typo: #Modifer vs. #Modifier.
In your query, you use #Modifier:
"INSERT INTO Weapons (Name, APPower, HEPower, Range, Modifier)
VALUES(#name, #APPower, #HEPower, #Range, #Modifier)"
But you specify the parameter name on the command as #Modifer:
com.Parameters.Add("#Modifer", SqlDbType.VarChar).Value = currentWeapon.Modifier

Related

How to execute query and store data of a column in a variable in VB.net?

I have the following code where I am trying to execute a query and store the value from the database in two variables. Depending on the variables, I would like to tick a checkbox and add some text to a textbox.
Here is the code:
Try
Dim cn As SqlConnection
Dim strCnn As String = ConfigurationManager.ConnectionStrings("agilityconnectionstring").ConnectionString
cn = New SqlConnection(strCnn)
cn.Open()
Dim comm As New SqlCommand("select IsCompleted, CompletionDate from managerchecklist where ID = 53 and QuestionID = 1", cn)
comm.CommandType = CommandType.Text
Dim ds As SqlDataReader
ds = comm.ExecuteReader()
If ds.HasRows Then
While ds.Read
IsComplete = ds.Item("IsCompleted").ToString()
CompleteDate = ds.Item("CompletionDate").ToString()
identifytasks_done.Checked = True
identifytasks_date.Attributes.Add("style", "display:block")
identifytasks_date.Text = CompleteDate
End While
End If
''Close your connections and commands.
cn.Close()
Catch ex As Exception
''Handle error if any
End Try
But I seem to be going wrong somewhere. Can anyone please help me?
Depending on the variables, I would like to tick a checkbox and add some text to a textbox.
Have an If Statement to check the variables whether it is complete
If IsComplete = "complete" Then
identifytasks_done.Checked = True
identifytasks_date.Attributes.Add("style", "display:block")
identifytasks_date.Text = CompleteDate
End If
Move the checking to SQL statement
Dim comm As New SqlCommand(
"select IsCompleted, CompletionDate from " +
"managerchecklist where ID = 53 and QuestionID = 1 and "
"IsCompleted = 'complete'",
cn)
Consider using parameter SQL instead to prevent SQL injection
I would recommend a Using statement for SQL queries and also parameters.
Get the values from SQL then use an IF statement to do whatever based on the values.
Assuming IsCompleted is a bit field in SQL....
Dim isCompleted As Boolean
Dim completedDate As Date
Using con As New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("agilityconnectionstring").ConnectionString)
Using cmd As New SqlClient.SqlCommand("SELECT [IsCompleted], [CompletionDate] FROM managerchecklist where [ID] = #managerchecklistID and [QuestionID] = #questionID", con)
cmd.Parameters.Add("#managerchecklistID", SqlDbType.Int).Value = 53
cmd.Parameters.Add("#questionID", SqlDbType.Int).Value = 1
con.Open()
Using reader As SqlClient.SqlDataReader = cmd.ExecuteReader
While reader.Read
'Index in order of the columns in the SELECT statement
If reader.GetSqlBoolean(0).IsNull = False Then isCompleted = reader.GetSqlBoolean(0)
If reader.GetSqlDateTime(1).IsNull = False Then completedDate = reader.GetSqlDateTime(1)
End While
End Using
End Using
End Using
If isCompleted Then
identifytasks_done.Checked = True
identifytasks_date.Attributes.Add("style", "display:block")
identifytasks_date.Text = completedDate
End If
You could place this in a Sub of it's own with managerchecklistID and questionID as arguments then set the parameter values with the arguments
cmd.Parameters.Add("#managerchecklistID", SqlDbType.Int).Value = managerchecklistID
cmd.Parameters.Add("#questionID", SqlDbType.Int).Value = questionID

Update Query Doesn't Work But No Error

(I code VB.NET and use ms access 2016 as database)
I execute this query but nothing happen. I wonder whats wrong. no error when i run it. i debugged it and all the values in the variables are also correct.
no changes happened in my db too
If Not (TextBoxID.Text = "" Or TextBoxNama.Text = "") Then
Try
Dim sqlquery As String = "UPDATE tblEmployees SET Nama = #nama WHERE IDEmployee = #ide"
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#ide", TextBoxID.Text)
.Parameters.AddWithValue("#nama", TextBoxNama.Text)
.Connection = FormMain.conn
.ExecuteNonQuery()
End With
ButtonEdit.Text = "EDIT"
ButtonEdit.Image = My.Resources.edit
GroupBox1.Enabled = False
ButtonNew.Enabled = True
Catch ex As Exception
MsgBox(ex.Message)
End Try
Else
MsgBox("Data cannot be empty!")
End If
The problem is that MS Access doesn't have named parameters - but rather positional parameters.
So you must specify the parameters in the correct order in which they appear in your SQL statement. And you're not doing to right now.
Change your code to this:
If Not (TextBoxID.Text = "" Or TextBoxNama.Text = "") Then
Try
Dim sqlquery As String = "UPDATE tblEmployees SET Nama = #nama WHERE IDEmployee = #ide"
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#nama", TextBoxNama.Text)
.Parameters.AddWithValue("#ide", TextBoxID.Text)
.Connection = FormMain.conn
.ExecuteNonQuery()
You must set the value for #nama first, before you set the value for #ide, since that's the order in which these parameters appear in your MS Access SQL statement.

ORA-01036: illegal variable name/number - Insert Query

I am getting the ORA-01036: illegal variable name/number error in my vb.net application
Please take a look and help me.
Thanks in advance.
Dim sSQL As String
sSQL = "INSERT INTO PSLSC_PSL_NOMINATION ( NOMINATION_ID, NOM_TYPE, PROPOSED_STATUS, COMMODITY_TEAM, COMMODITY_DESC, COMMODITY_CODE, PARENT_ID, SUPPLIER_ID, SUPPLIER_NAME, ADDRESS, COUNTRY, TELEPHONE, CONTACT, WEBSITE, EMAIL, SPEND, TECHSOURCE_SCORE, ESAC_SCORE, PAYMENT_TERMS, MSA_CONTRACT, BUSA_CONTRACT, LEAN_CHAMPION, LEAN_CHAMPION_NAME, QUALITY, ON_TIME_DELIVERY, SUPPORTS_ESOURCING, COMPLIANCE_REQUIREMENT, FLEXIBILITY, CAP_MEET_DELIVERY_FREQ, NOMINATING_BUSINESS_UNIT, NOMINATING_REGION, OWNER, NOMINATED_DATE, COMMENTS, SENDER, SENDER_EMAIL )"
sSQL = sSQL & " VALUES ( :NOMINATION_ID,:NOM_TYPE,:PROPOSED_STATUS,:COMMODITY_TEAM,:COMMODITY_DESC,:COMMODITY_CODE,:PARENT_ID,:SUPPLIER_ID,:SUPPLIER_NAME,:ADDRESS,:COUNTRY,:TELEPHONE,:CONTACT,:WEBSITE,:EMAIL,:SPEND,:TECHSOURCE_SCORE,:ESAC_SCORE,:PAYMENT_TERMS,:MSA_CONTRACT,:BUSA_CONTRACT,:LEAN_CHAMPION,:LEAN_CHAMPION_NAME,:QUALITY,:ON_TIME_DELIVERY,:SUPPORTS_ESOURCING,:COMPLIANCE_REQUIREMENT,:FLEXIBILITY,:CAP_MEET_DELIVERY_FREQ,:NOMINATING_BUSINESS_UNIT,:NOMINATING_REGION,:OWNER,:NOMINATED_DATE,:COMMENTS,:SENDER,:SENDER_EMAIL )"
Dim obj_id As Decimal
obj_id = getNewSRM_OBJ_ID(cn_SRM)
Dim cn As OracleConnection = New OracleConnection(cn_proc)
Dim cmd As OracleCommand = New OracleCommand(sSQL, cn)
cmd.Parameters.Add(":NOMINATION_ID", obj_id)
cmd.Parameters.Add(":NOM_TYPE", row.NOM_TYPE)
cmd.Parameters.Add(":PROPOSED_STATUS", row.PROPOSED_STATUS)
cmd.Parameters.Add(":COMMODITY_TEAM", row.COMMODITY_TEAM)
cmd.Parameters.Add(":COMMODITY_DESC", row.COMMODITY_DESC)
cmd.Parameters.Add(":COMMODITY_CODE", row.COMMODITY_CODE)
cmd.Parameters.Add(":PARENT_ID", row.PARENT_ID)
cmd.Parameters.Add(":SUPPLIER_ID", row.SUPPLIER_ID)
cmd.Parameters.Add(":SUPPLIER_NAME", row.SUPPLIER_NAME)
cmd.Parameters.Add(":ADDRESS", row.ADDRESS)
cmd.Parameters.Add(":COUNTRY", row.COUNTRY)
cmd.Parameters.Add(":PHONE", row.PHONE)
cmd.Parameters.Add(":CONTACT", row.CONTACT)
cmd.Parameters.Add(":WEBSITE", row.WEBSITE)
cmd.Parameters.Add(":EMAIL", row.EMAIL)
cmd.Parameters.Add(":SPEND", row.SPEND)
cmd.Parameters.Add(":TECHSOURCE_SCORE", row.TECHSOURCE_SCORE)
cmd.Parameters.Add(":ESAC_SCORE", row.ESAC_SCORE)
cmd.Parameters.Add(":PAYMENT_TERMS", row.PAYMENT_TERMS)
cmd.Parameters.Add(":MSA_CONTRACT", row.MSA_CONTRACT)
cmd.Parameters.Add(":BUSA_CONTRACT", row.BUSA_CONTRACT)
cmd.Parameters.Add(":LEAN_CHAMPION", row.LEAN_CHAMPION)
If Not row.IsLEAN_CHAMPION_NAMENull Then
cmd.Parameters.Add(":LEAN_CHAMPION_NAME", row.LEAN_CHAMPION_NAME)
Else
cmd.Parameters.Add(":LEAN_CHAMPION_NAME", System.DBNull.Value)
End If
cmd.Parameters.Add(":QUALITY", row.QUALITY)
cmd.Parameters.Add(":ON_TIME_DELIVERY", row.ON_TIME_DELIVERY)
cmd.Parameters.Add(":SUPPORTS_ESOURCING", row.SUPPORTS_ESOURCING)
cmd.Parameters.Add(":COMPLIANCE_REQUIREMENT", row.COMPLIANCE_REQUIREMENT)
cmd.Parameters.Add(":FLEXIBILITY", row.FLEXIBILITY)
cmd.Parameters.Add(":CAP_MEET_DELIVERY_FREQ", row.CAP_MEET_DELIVERY_FREQ)
cmd.Parameters.Add(":NOMINATING_BUSINESS_UNIT", row.NOMINATING_BUSINESS_UNIT)
cmd.Parameters.Add(":NOMINATING_REGION", row.NOMINATING_REGION)
cmd.Parameters.Add(":OWNER", row.OWNER)
cmd.Parameters.Add(":NOMINATED_DATE", row.NOMINATED_DATE)
cmd.Parameters.Add(":COMMENTS", row.COMMENTS)
cmd.Parameters.Add(":SENDER", row.SENDER)
cmd.Parameters.Add(":SENDER_EMAIL", row.SENDER_EMAIL)
Try
cn.Open()
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Catch ex As Exception
LOG_ERROR(ex.Message, sSQL, cn.ConnectionString, ex.Source)
End Try
You can also get this error when you omit the bind variable reference from the SQL but you create a Parameter for it. Ask me how I know this.
Example taken from above that might repro it (notice "PROPOSED_STATUS" is not in the SQL but is being added as Parameter:
sSQL = "INSERT INTO PSLSC_PSL_NOMINATION ( NOMINATION_ID, NOM_TYPE ) VALUES ( :NOMINATION_ID,:NOM_TYPE )"
Dim obj_id As Decimal = getNewSRM_OBJ_ID(cn_SRM)
Dim cn As OracleConnection = New OracleConnection(cn_proc)
Dim cmd As OracleCommand = New OracleCommand(sSQL, cn)
cmd.Parameters.Add(":NOMINATION_ID", obj_id)
cmd.Parameters.Add(":NOM_TYPE", row.NOM_TYPE)
cmd.Parameters.Add(":PROPOSED_STATUS", row.PROPOSED_STATUS)
Try
cn.Open()
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
Catch ex As Exception
LOG_ERROR(ex.Message, sSQL, cn.ConnectionString, ex.Source)
End Try

Insert and Select at the same time in a stored procedure

I have the following stored procedure:
create procedure Insert_Maintenance
(
#PlateNo nvarchar(10),
#MaintenanceType nvarchar(150),
#Name nvarchar(300),
#MaintenanceDate date,
#Qty int,
#IndivisualVal float,
#TotalVal float,
#Notes nvarchar(300)
)
as
insert into Maintenance(MaintenanceNo, PlateNo, MaintenanceType, AutoCenterNo,MaintenanceDate, Qty, IndivisualVal, TotalVal, Notes)
values ((1+(select Max(MaintenanceNo) from Maintenance)), #PlateNo, #MaintenanceType, (select AutoCenterNo from AutoCenter where Name = #Name), #MaintenanceDate, #Qty, #IndivisualVal, #TotalVal, #Notes)
Select Max(MaintenanceNo) AS MNo from Maintenance
A user will insert new maintenance operation via VB.NET interface. The information of the maintenance will be inserted into the database. The ID of the maintenance will increase by 1; as it is shown in the code. Since this is the case, after inserting the information I want to show a message that tells the user that information entered correctly and the ID of this operation is the value of MNo.
Basically, the problem is not with the VB.NET code because the message works fine but the problem is related to the select statement that shows the maintenance ID to the user.
The code in VB.NET
Dim ConnectString As String
ConnectString = ""
Dim connection As New SqlConnection(ConnectString)
'Dim parm1 As SqlParameter
'parm1 = New SqlParameter("#MaintenanceNo", SqlDbType.Int)
'parm1.Value = MaintenanceNoTextBox.Text
Dim parm2 As SqlParameter
parm2 = New SqlParameter("#PlateNo", SqlDbType.NVarChar)
parm2.Value = PlateNoComboBox.Text
Dim parm3 As SqlParameter
parm3 = New SqlParameter("#MaintenanceType", SqlDbType.NVarChar)
parm3.Value = MaintenanceTypeTextBox.Text
Dim parm4 As SqlParameter
parm4 = New SqlParameter("#Name", SqlDbType.NVarChar)
parm4.Value = NameComboBox.Text
Dim parm5 As SqlParameter
parm5 = New SqlParameter("#MaintenanceDate", SqlDbType.Date)
parm5.Value = MaintenanceDateDateTimePicker.Value
Dim parm6 As SqlParameter
parm6 = New SqlParameter("#Qty", SqlDbType.Int)
parm6.Value = QtyTextBox.Text
Dim parm7 As SqlParameter
parm7 = New SqlParameter("#IndivisualVal", SqlDbType.Float)
parm7.Value = IndivisualValTextBox.Text
Dim parm8 As SqlParameter
parm8 = New SqlParameter("#TotalVal", SqlDbType.Float)
parm8.Value = TotalValTextBox.Text
Dim parm9 As SqlParameter
parm9 = New SqlParameter("#Notes", SqlDbType.NVarChar)
parm9.Value = NotesTextBox.Text
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = connection
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Insert_Maintenance"
'cmd.Parameters.Add(parm1)
cmd.Parameters.Add(parm2)
cmd.Parameters.Add(parm3)
cmd.Parameters.Add(parm4)
cmd.Parameters.Add(parm5)
cmd.Parameters.Add(parm6)
cmd.Parameters.Add(parm7)
cmd.Parameters.Add(parm8)
cmd.Parameters.Add(parm9)
Try
connection.Open()
cmd.ExecuteNonQuery()
Dim dreader As SqlDataReader
dreader = cmd.ExecuteReader()
Dim a As String
a = dreader("MNo").ToString
MessageBox.Show("Information entered, ID is " + a)
dreader.Close()
'MaintenanceNoTextBox.Text = ""
PlateNoComboBox.Text = ""
MaintenanceTypeTextBox.Text = ""
NameComboBox.Text = ""
'MaintenanceDateDateTimePicker.Value = ""
QtyTextBox.Text = ""
IndivisualValTextBox.Text = ""
TotalValTextBox.Text = ""
NotesTextBox.Text = ""
Catch ex As Exception
MessageBox.Show("Something wrong (" + ex.Message + ")")
Finally
connection.Close()
End Try
Any suggestions guys !! Thanks
To solve your problem you need to just change one line and remove a bunch of unnecessary code
Dim cmd As SqlCommand = New SqlCommand()
cmd.Connection = connection cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Insert_Maintenance"
.... you need to build the parameters collection here .....
Try
connection.Open()
Dim result = cmd.ExecuteScalar() ' <- Instead of ExecuteNonQuery '
if result IsNot Nothing Then
Console.WriteLine("The Mno is:" & Convert.ToInt32(result)
End If
ExecuteScalar returns the first column of the first row in your results. This should resolve the VB.NET side of your code. Of course, if you don't need to control the values inserted in the column MaintenanceNo then the next action to take is to set the Identity property to Yes in the field properties. In this way you could remove the last lines of your storedprocedure and forget to pass anything for the MaintenaceNo field
INSERT INTO Maintenance(PlateNo, MaintenanceType, AutoCenterNo,MaintenanceDate, Qty,
IndivisualVal, TotalVal, Notes)
VALUES (#PlateNo, #MaintenanceType,
(select AutoCenterNo from AutoCenter where Name = #Name),
#MaintenanceDate, #Qty, #IndivisualVal, #TotalVal, #Notes)
SELECT SCOPE_IDENTITY()
I think ID of Maintainance table should be auto-increment. For achieving that you can set Is Identity to Yes
In the end of insert if you want the ID than you can get by
Select SCOPE_IDENTITY()
If you want to increment ID manually then try this :
declare #newid int
Select #newid = Max(ISNULL(MaintenanceNo, 0)) from Maintenance
set #newid = #newid + 1
then use #newid for insert and in the end Select #newid

Update statment using vb.net to update all fields

I create table using sql developer
create table tablenodes
(
nodeNo int ,
nodeName varchar2(50),
centerX int ,
centerY int,
radius number(7,2),
fileNo int
)
And I want to update all fields in this table, so I wrote the following code:
Friend Function UpdateNodeToTable(ByVal FN As Integer, ByVal nd As classNode) As Boolean
Try
Dim con As New OracleConnection
con.ConnectionString = "Persist Security Info=False;User ID=manal;password=manal;Data Source=xe"
con.Open()
Dim cmd As New OracleCommand
cmd.CommandType = CommandType.Text
cmd.Connection = con
cmd.CommandText = "update tablenodes set nodeName=#NodeName, centerX = #NodeCenterX," & _
"centerY= #NodeCenterY , radius= #NodeRadius where nodeNo= #nodeNum and fileno= #FileNum"
cmd.Parameters.Add("#NodeNum", OracleDbType.Int32).Value = nd.pID
cmd.Parameters.Add("#NodeName", OracleDbType.Varchar2).Value = nd.pName
cmd.Parameters.Add("#NodeCenterX", OracleDbType.Int32).Value = nd.pCenter.X
cmd.Parameters.Add("#NodeCenterY", OracleDbType.Int32).Value = nd.pCenter.Y
cmd.Parameters.Add("#NodeRadius", OracleDbType.Double).Value = nd.pRadius
cmd.Parameters.Add("#FileNum", OracleDbType.Int32).Value = FN
Dim success As Boolean
If cmd.ExecuteNonQuery() = 1 Then
success = True
Else
success = False
End If
cmd.Dispose()
con.Close()
con.Dispose()
Return success
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Function
I have a problem in updating statements, can't write it correctly, every time I try to edit it, gives me different error (ora-01036 illegal variable name/number, missing expression, invalid identifier).
The bind variables in you UPDATE statement should be prefixed by a colon, not the # symbol
cmd.CommandText = "update tablenodes set nodeName=:NodeName, centerX = :NodeCenterX," & _
"centerY= :NodeCenterY , radius= :NodeRadius where nodeNo= :nodeNum and fileno= :FileNum"
And there would be no prefix what you're setting the parameters
cmd.Parameters.Add("NodeNum", OracleDbType.Int32).Value = nd.pID
cmd.Parameters.Add("NodeName", OracleDbType.Varchar2).Value = nd.pName
cmd.Parameters.Add("NodeCenterX", OracleDbType.Int32).Value = nd.pCenter.X
cmd.Parameters.Add("NodeCenterY", OracleDbType.Int32).Value = nd.pCenter.Y
cmd.Parameters.Add("NodeRadius", OracleDbType.Double).Value = nd.pRadius
cmd.Parameters.Add("FileNum", OracleDbType.Int32).Value = FN