Add the same parameter twice and execute query - sql

Dim b as integer = 1
cmd = New SqlCommand
With cmd
.Connection = connecti
.CommandTimeout = 0
.CommandText = "INSERT INTO HEZDDD(ID,Number,Dates) VALUES (#Id,#Number,#Dates)"
With .Parameters
.AddWithValue("#ID", NextId())
.AddWithValue("#Dates", date.now)
If b = 1 Then
.AddWithValue("#Number", 1)
cmd.ExecuteNonQuery()
End if
If b>10 Then
.AddWithValue("#Number", 2)
cmd.ExecuteNonQuery()
End if
End With
End With
Looking forward to execute the same query twice using different parameters. The output of this simple query should be two rows.
This is simple example i didnt want to put entire code with around 25 parameters.

First use Parameters.Add(string parameterName, SqlDbType sqlDbType) to add parameters without values.
cmd.Parameters.Add("#ID", SqlDbType.Int);
Before you execute the command, provide the values for the parameters:
cmd.Parameters["#ID"].Value = NextId();
Actually, it's always better to use Parameters.Add(string parameterName, SqlDbType sqlDbType), even if you want to set the value immediately. If you use AddWithValue, the db type of the parameter has to be inferred from the value. It usually works well, but you might have some surprises. And because Add returns the added parameter, you can assign the value in the same line:
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = NextId();

It's already in the parameter collection, you just need to change the value on it on the second one.
.Parameters("#Number").Value = 2
Or out of the with..
cmd.Parameters("#Number").Value = 2

Related

Solution add textbox in SQL as string in vb.net

What is the solution if you see the code below there is a value (2000) then I want to change it to textbox so I can custom value.
Thanks
jack
Dim sql As String = "update GSDTS as t1 inner join IFGTS as t2 on t1.[ITM] = t2.[ITM] set t1.[CIU] = t2.[PRSOBNET]+2000 WHERE GDN = 'A.04.01.002.001'AND PNM=#PNM"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
conn.Open()
cmd.ExecuteNonQuery()
End Using
You can just add another parameter to your query like here
' Read the textbox value here'
Dim newValue as Integer
Int32.TryParse(txtInput.Text, newValue)
' Put the parameter placeholder instead of a constant'
Dim sql As String = "update GSDTS as t1 inner join IFGTS as t2
on t1.[ITM] = t2.[ITM]
set t1.[CIU] = t2.[PRSOBNET]+#addvalue
WHERE GDN = 'A.04.01.002.001'AND PNM=#PNM"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
' Add the other parameter and its value before the old one. See note below'
cmd.Parameters.AddWithValue("#addvalue", newValue)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
conn.Open()
cmd.ExecuteNonQuery()
End Using
Also, take a look at how to replace AddWithValue with a single line Add. AddWithValue is dangerous because it can misrepresents your value when working with dates or decimals and it is inefficient with strings
** IMPORTANT **
You are working with the OleDb provider. In this context the parameters should be added in the same order in which their placeholders appear in the string. So the new parameter should be added before the #PNM one otherwise they will be read in the wrong order when the query is executed.
Your SQL syntax wouldn't work for any RDBMS I know of and you didn't tag the backend. That might be solely a reason for it not to work at all, you should start by correcting it.
Second, do not use AddWithValue but Add and explicitly specify your data type.
Having said that, for example MS SQL server as a backend:
Dim sql As String = <sql>UPDATE GSDTS
SET [CIU] = t2.[PRSOBNET] + #addVal
FROM GSDTS AS t1
INNER JOIN IFGTS AS t2
ON t1.[ITM] = t2.[ITM]
WHERE t1.GDN = 'A.04.01.002.001'
AND t1.PNM = #PNM;</sql>
Dim addVal As Integer = Nothing
If Integer.TryParse(txtAdd.Text, addVal) Then
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add("#addVal", OleDbType.Integer).Value = addVal
cmd.Parameters.Add("#PNM", OleDbType.VarChar).Value = ComboBox1.SelectedValue
conn.Open()
cmd.ExecuteNonQuery()
End Using
End If
Note that order of variable declarations are same as their order they are used in the query. That is a necessity with OleDb (positional arguments). If your backend is something like MS SQL server then prefer using backend specific SqlConnection, SqlCommand (then you can also use named parameters).

adding sqlparameter without name

I'm trying to create a sub to add as many parameters as I want, I used to do this in vb6 but here in vb.net it requires me to provide the parameter name (.add(#parameter, value)). I need to find a way to do it without knowing the parameter name, i used to send the parameters using the parameter order in the stored procedure, here the code:
Public Sub EjecutarSP(ByVal SP As String, ByVal ParamArray Parametros() As Object)
Dim cnn As New SqlConnection(ConfigurationSettings.AppSettings("connString").ToString)
Dim cmd As New SqlCommand(SP, cnn)
Dim i As Integer
Dim Param As SqlParameter
Try
For i = 0 To UBound(Parametros)
Param = New SqlParameter("str", Parametros(i))
cmd.Parameters.Add(Param)
Next
cmd.CommandTimeout = 0
cmd.CommandType = CommandType.StoredProcedure
If cmd.Connection.State <> ConnectionState.Open Then cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd = Nothing
Catch ex As Exception
Err.Raise(1000, "EjecutarSP", ex.Message)
End Try
End Sub
thanks
AFAIK the SqlClient doesn't support nameless parameters
From here:
Nameless, also called ordinal, parameters are not supported by the .NET Framework Data Provider for SQL Server.
However, instead of explicitly creating the parameters, you could fetch the parameters for the Proc with DeriveParameters, once you are connected.
Assuming you wish to blindly wish to trust the order of the parameters to match the parameters of the Proc, simply set the .Value of the parameters at the given index.
Dim cmd As New SqlCommand(SP, cnn)
...
SqlCommandBuilder.DeriveParameters(cmd)
For i = 0 To UBound(Parametros)
cmd.Parameters(i).Value = Parametros(i)
Next
Just reset the name to nothing (null) once the parameter has been added, something like this:
For i = 0 To UBound(Parametros)
Param = New SqlParameter("str", Parametros(i))
cmd.Parameters.Add(Param)
Param.ParameterName = Nothing
Next
You don't have to explicity name or type parameters. There are actually a couple of ways to execute stored procs without naming each parameter. Here is one way using Microsoft's old EnterpriseLibrary (which I still like in 2019).
NB: in VB.NET the size of the parameter array is one less than the number of parameters in the stored proc.
Dim dt As System.Data.DataTable
Dim arrParameters(6) As Object
arrParameters(0) = "Hello"
arrParameters(1) = "World"
arrParameters(2) = "Lorem"
arrParameters(3) = "Ipsum"
arrParameters(4) = "Dolor"
arrParameters(5) = "Blabla"
arrParameters(6) = 12345
Try
Dim db As Microsoft.Practices.EnterpriseLibrary.Data.Database = Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase("TheNameOfYourConnectionStringInWebConfig")
dt = db.ExecuteDataSet("TheNameOfYourStoredProcedure", arrParameters).Tables(0)
Catch ex As Exception
End Try

SQL Error "One or more required Parameters are missing a value."

Its telling me im missing a Parameter here, but I can't seem to figure out why. I have 2 Parameters, and 2 values given underneath the cmd statement.
Thanks in advance.
cmd = New OleDbCommand("UPDATE Inventory SET CurBalDue = (CurBalDue + ?) WHERE CustID = ?", Con)
Prm = New OleDbParameter("CurBalDue", Totcost)
cmd.Parameters.Add(Prm)
Prm = New OleDbParameter("CustID", lblCustID.Text)
cmd.Parameters.Add(Prm)
cmd.ExecuteNonQuery()
Dim SQl As string = "UPDATE Inventory SET CurBalDue = (CurBalDue + ?)
WHERE CustID = ?"
Using cmd as New OleDbCommand(SQL, con)
cmd.Parameters.AddWithValue("#p1", Totcost)
cmd.Parameters.AddWithValue("#p2", lblCustID.Text)
cmd.ExecuteNonQuery()
End Using ' dispose of the disposable
AddWithValue adds a new parameter to the collection, with a value in one step. Also, OleDB does not support named params, so you are fooling yourself a little by using them as such. They are just positional placeholders, add params in the order they appear in the SQL.
I have no way to tell what data type these critters are. Totcost may well have to be converted:
cmd.Parameters.AddWithValue("#p1", Convert.ToDecimal(Totcost))

Determining if a query returns 'no rows' in vb.net

I am using MS SQL Server as my database and VB.NET as my back-end.
I want to determine if my query in sql command text returns no rows.
I tried to have a query that returns no rows, and then give its value to a text box which became 0. (integer)
The problem now, is that when I test it in an If condition, it doesn't work.
The code is like this:
If (Query that returns no rows) = 0 Then
'condition
Else
'condition
End If
I tried a blank string, but it still does not work. Please help!
If possible, please give the simples solution to the problem.
Thank you in advance!
#podiluska is right. You will have to execute the command. As I can see you have assigned value for the CommandText property of Command object that’s the query you want to execute. In order to execute the command, you must have an open active connection followed by call to Execute method on command object. Following pseudo code might help:
Public Sub Temp(ByVal connectionString As String)
Dim queryString As String = _
" select * from example where id = 999;"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
Try
If reader.Read() Then
'If condition
Else
'condition with no results
End If
Finally
reader.Close()
End Try
End Using
End Sub
Dim RowsReturned As Integer
Cmd.CommandText = "SELECT * FROM tblExample WHERE PKeyNo =999"
cmd.CommandType = CommandType.Text
RowsReturned = cmd.ExecuteScalar()
If RowsReturned = 0 Then
'No rows
Else
'Has Rows

vb.net - Object reference not set to an instance of object

I got this error when trying to use parameters to my sql statement, but it works fine when not use it. My codes are below:
Dim i As String
Dim sql as String
sql = "SELECT * FROM tblStaff WHERE Username = #User AND Password = #Pass"
myCommand = New SqlCommand(sql, myConnection)
myCommand.Parameters.AddWithValue("#User", txtUser.Text)
myCommand.Parameters.AddWithValue("#Pass", txtPassword.Text)
i = myCommand.ExecuteScalar
txtUserType.Text = i.ToString
And when I comment on txtUserType.Text = i.ToString, it works fine. Any idea?
ExecuteScalar should only give you one value back, like an integer. So if you specify only one column in your SQL statement for example (Select usertype from tblStaff...) the executescalar should return an integer (if that column is a number).
Then it should work.
and by the way.. you don't have to use ToString on a variable that is a string. Just use the variables name
txtUserType.Text = i