Must declare the scalar variable, but its declared - sql

I've declared a variable in the code, but I'm clueless on how its still showing the error, any ideas?
When I remove the WHERE clauses after it shows every row, but when putting them in I get "Must declare the scalar variable #startdata".
connect()
cmd.CommandText = "SELECT h_initials, h_date, h_hours FROM [h_holidays] WHERE h_date >= #startdata AND h_date < #enddata "
cmd.Parameters.Clear()
cmd.Parameters.Add("#startdata", SqlDbType.DateTime).Value = datetime_date.Value
cmd.Parameters.Add("#enddata", SqlDbType.DateTime).Value = datetime_2.Value
cmd.ExecuteScalar()
Dim dataAdapter_holidays_all = New SqlDataAdapter(cmd.CommandText, con.ConnectionString)
Dim table_holidays_all As New DataTable()
table_holidays_all.Locale = System.Globalization.CultureInfo.InvariantCulture
dataAdapter_holidays_all.Fill(table_holidays_all)
Me.bs_holidays_all.DataSource = table_holidays_all
dgv_holidays_all.DataSource = bs_holidays_all
disconnect()
dgv_holidays_all.RowHeadersWidth = "28"
dgv_holidays_all.Columns(0).HeaderText = "User:"
dgv_holidays_all.Columns(1).HeaderText = "Date:"
dgv_holidays_all.Columns(2).HeaderText = "Hours:"
dgv_holidays_all.EnableHeadersVisualStyles = False
I've tried .addwithvalue on the parameters with still no luck.

No, it's not declared. Your code is rather all over the place. You first create a SqlCommand object, add parameters to it and call its ExecuteScalar method, but that makes no sense because you are retrieving more than one value. You then create a SqlDataAdapter with the same SQL but you don't add any parameters to its SelectCommand.
What you should be doing is creating a SqlDataAdapter, getting its SelectCommand and adding the parameters to it, e.g.
Dim sql = "SELECT h_initials, h_date, h_hours FROM [h_holidays] WHERE h_date >= #startdata AND h_date < #enddata"
Dim adapter As New SqlDataAdapter(sql, con)
With adapter.SelectCommand.Parameters
.Add("#startdata", SqlDbType.DateTime).Value = datetime_date.Value
.Add("#enddata", SqlDbType.DateTime).Value = datetime_2.Value
End With
No additional SqlCommand object. No pointless call to ExecuteScalar.

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

if the input value is in between two values then display the result

I have a SQL table with three columns "From","To" and "Equivalent Value". Each value is shown below:
From To Equivalent Value
1,001.00 2,000.00 200.00
2,001.00 3,000.00 300.00
Now if the user enters the value "1,200.00" in textbox1 it will display the result value to textbox2 which is "200.00" because that is the corresponding value of between "From" and "To.
Another condition, if the user enters the value "2,500.00" in textbox1 it will display the value "300.00".
So far, I have tried this code but no luck:
Dim conn As SqlConnection = SQLConn()
Dim da As New SqlDataAdapter
Dim dt As New DataTable
conn.Open()
Dim cmd As New SqlCommand("", conn)
Dim result As String
cmd.CommandText = "SELECT [Equivalent Value] FROM tblSSS"
result = IIf(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar)
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
If result <> "" Then
If TextBox1.Text >= dt.Rows(0)(1).ToString() And TextBox1.Text <= dt.Rows(0)(2).ToString() Then
TextBox2.Text = dt.Rows(0)(3).ToString()
End If
End If
If I have got this right I think there are a couple of things I would change which may help you:
Use Using. This will dispose of the SQL objects once finished with.
Use SqlParameters. This will help with filtering your data.
Remove the use of SqlDataAdapter. In this case I don't feel it's needed.
The use of IIf. I will be using If which has replaced IIf.
With these in mind I would look at something like this:
Dim fromValue As Decimal = 0D
Dim toValue As Decimal = 0D
If Decimal.TryParse(TextBox1.Text, fromValue) AndAlso Decimal.TryParse(TextBox1.Text, toValue) Then
Dim dt As New DataTable
Using conn As SqlConnection = SQLConn,
cmd As New SqlCommand("SELECT [Equivalent Value] FROM tblSSS WHERE [From] >= #From AND [To] <= #To", conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#From", .SqlDbType = SqlDbType.Decimal, .Value = fromValue})
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#To", .SqlDbType = SqlDbType.Decimal, .Value = toValue})
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count = 1 Then
TextBox2.Text = If(IsDBNull(dt.Rows(0).Item("Equivalent Value")), "0", dt.Rows(0).Item("Equivalent Value").ToString)
End If
End If
Note the use of Decimal.TryParse:
Converts the string representation of a number to its Decimal equivalent. A return value indicates whether the conversion succeeded or failed.
This is an assumption that the From and To fields in your database are Decimal.
Now to explain the difference between IIf and If. IIf executes each portion of the statement even if it's true whilst If executes only one portion. I won't go into detail as many others on here have done that already. Have a look at this answer.
As per Andrew Morton's comment and more in line with what the OP attempted here is a solution that uses ExecuteScaler.
ExecuteScaler executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.
With this in mind:
'I reset the value of TextBox2.Text. You may not want to.
TextBox2.Text = ""
Dim fromValue As Decimal = 0D
Dim toValue As Decimal = 0D
If Decimal.TryParse(TextBox1.Text, fromValue) AndAlso Decimal.TryParse(TextBox1.Text, toValue) Then
Using conn As SqlConnection = SQLConn,
cmd As New SqlCommand("SELECT [Equivalent Value] FROM tblSSS WHERE [From] >= #From AND [To] <= #To", conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#From", .SqlDbType = SqlDbType.Decimal, .Value = fromValue})
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#To", .SqlDbType = SqlDbType.Decimal, .Value = toValue})
conn.Open()
Try
TextBox2.Text = cmd.ExecuteScalar().ToString()
Catch ex As Exception
End Try
End Using
End If
I have used the example on the ExecuteScaler MSDN documentation. You might want to look into handling the exception on the Try Catch a little better and not letting it go to waste.
You may want to place this code on the TextBox1.Leave method or maybe on a Button.Click method. That's totally up to you.
There may a few changes you may need to make however I think this will give you a few ideas on how to move ahead with your code.
Hope it Helps...
Dim connetionString As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "SELECT [Equivalent Value] FROM tblSSS WHERE [FROM]<=" & Val(TextBox1.Text) & " AND [TO]>= " & Val(TextBox1.Text)
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
cmd = New SqlCommand(sql, cnn)
Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
cmd.Dispose()
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try

How can I read a specific column in a database?

I hava a Table named DTR_Table it has 8 columns in it namely:
EmployeeID,Date,MorningTime-In,MorningTime-Out,AfternoonTime-In,AfternoonTime-Out,UnderTime,Time-Rendered.I want to read the column "AfternoonTime-In".
Following is my code. It reads my "AfternoonTime-In" field, but it keeps on displaying "Has Rows" even if there is nothing in that column.
How can I fix this?
Connect = New SqlConnection(ConnectionString)
Connect.Open()
Dim Query1 As String = "Select [AfternoonTime-Out] From Table_DTR Where Date = #Date and EmployeeID = #EmpID "
Dim cmd1 As SqlCommand = New SqlCommand(Query1, Connect)
cmd1.Parameters.AddWithValue("#Date", DTRform.datetoday.Text)
cmd1.Parameters.AddWithValue("#EmpID", DTRform.DTRempID.Text)
Using Reader As SqlDataReader = cmd1.ExecuteReader()
If Reader.HasRows Then
MsgBox("Has rows")
Reader.Close()
Else
MsgBox("empty")
End If
End Using`
After returning the DataReader you need to start reading from it if you want to extract values from your query.
Dim dt = Convert.ToDateTime(DTRform.datetoday.Text)
Dim id = Convert.ToInt32(DTRform.DTRempID.Text)
Using Connect = New SqlConnection(ConnectionString)
Connect.Open()
Dim Query1 As String = "Select [AfternoonTime-Out] From Table_DTR
Where Date = #Date and EmployeeID = #EmpID"
Dim cmd1 As SqlCommand = New SqlCommand(Query1, Connect)
cmd1.Parameters.Add("#Date", SqlDbType.DateTime).Value = dt
cmd1.Parameters.Add("#EmpID", SqlDbType.Int).Value = id
Using Reader As SqlDataReader = cmd1.ExecuteReader()
While Reader.Read()
MessageBox.Show(Reader("AfternoonTime-Out").ToString())
Loop
End Using
End Using
Note that I have changed the AddWithValue with a more precise Add specifying the parameter type. Otherwise, your code will be in the hand of whatever conversion rules the database engine decides to use to transform the string passed to AddWithValue to a DateTime.
It is quite common for this conversion to produce invalid values especially with dates

vb.net SQL causing - "Must declare the scalar variable "

I've been stuck on this error for a while, in vb.net trying to connect to SQL and pull data from a table within a day, using parameters to do this, a datetimepicker - the data saved to SQL is in a custom datetime format dd/MM/yyyy HH:mm:ss,
When i execute my code i get
"Must declare the scalar variable "#line"
When i remove the code " WHERE [line] = #line and date >= #startdata AND date < #enddata " it works but shows all the data without the date range as it should.
connect()
DataGridView1.AutoGenerateColumns = True
cmd.Parameters.Clear()
cmd.CommandText = #"SELECT board, defect, date, detail_x, detail_y,
detail_width, detail_height
FROM [sqlccmdefects]
WHERE [line] = #line
and date >= #startdata
AND date < #enddata";
cmd.Parameters.Add("#line", SqlDbType.VarChar, 30).Value = Form1.line.Text
cmd.Parameters.Add("#startdata", SqlDbType.DateTime).Value = DateTimePicker1.Value
cmd.Parameters.Add("#enddata", SqlDbType.DateTime).Value = DateTimePicker2.Value
cmd.ExecuteScalar()
Dim dataAdapter1 = New SqlDataAdapter(cmd.CommandText, con.ConnectionString)
Dim table1 As New DataTable()
table1.Locale = System.Globalization.CultureInfo.InvariantCulture
dataAdapter1.Fill(table1)
Me.BindingSource1.DataSource = table1
DataGridView1.DataSource = BindingSource1
disconnect()
All i get is a blank Datagridview with the scalar error.
There looks to be a couple of issues in the code you posted,
Try this:
'SQL Connection
Dim sqlCon As New SqlConnection("Server=.;Database=dummy;Trusted_Connection=True;")
'SQL Command
Dim sqlCmd As New SqlCommand("", sqlCon)
sqlCmd.CommandText = "SELECT board, defect, date, detail_x, detail_y, detail_width, detail_height FROM [sqlccmdefects] WHERE [line] = #line and date >= #startdata AND date < #enddata"
'SQL Command Params
sqlCmd.Parameters.Add("#line", SqlDbType.VarChar, 30).Value = "WHATEVER"
sqlCmd.Parameters.Add("#startdata", SqlDbType.DateTime).Value = "2015-07-21"
sqlCmd.Parameters.Add("#enddata", SqlDbType.DateTime).Value = "2015-07-23"
'Data Adapters
Dim dataAdapter1 = New SqlDataAdapter(sqlCmd)
Dim table1 As New DataTable()
'NOT SURE WHAT THIS DOES?
table1.Locale = System.Globalization.CultureInfo.InvariantCulture
'Attach to the GV
dataAdapter1.Fill(table1)
DataGridView1.AutoGenerateColumns = True
BindingSource1.DataSource = table1
DataGridView1.DataSource = BindingSource1
ExecuteScalar is typically used when your query returns a single value. If it returns more, then the result is the first column of the first row.
Use cmd.ExecuteReader() or cmd.ExecuteNonQuery() instead of cmd.ExecuteScalar()
cmd.ExecuteScalar()
will execute the command – consuming the parameters – and throwing away any result (use ExecuteNonQuery when there is no result: saves setting up to return values).
When you fill the data adapter the command will be run again. But this time there are no parameters, and SQL fails on the first undefined identifier.
So: don't execute the command, instead pass the (unexecuted) command to the (single argument) data adapter constructor.

The parameterized query expects the parameter which was not supplied

I'm having a problem with my code:
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
list.Items.Clear()
cmd.CommandText = "SELECT * FROM borrow where (Department LIKE '%" & TextBox2.Text & "%')"
cmd.Connection = con
cmd.CommandType = CommandType.Text
con.Open()
rd = cmd.ExecuteReader()
If rd.HasRows = True Then
While rd.Read()
Dim listview As New ListViewItem
listview.Text = rd("ID").ToString
listview.SubItems.Add(rd("Department").ToString)
listview.SubItems.Add(rd("Purpose").ToString)
listview.SubItems.Add(rd("Items_Details").ToString)
listview.SubItems.Add(rd("Requested_by").ToString)
listview.SubItems.Add(rd("Approved_by").ToString)
listview.SubItems.Add(rd("Date").ToString)
listview.SubItems.Add(rd("Status").ToString)
listview.SubItems.Add(rd("Date_Returned").ToString)
list.Items.Add(listview)
End While
End If
con.Close()
Once I typed in the string in the textbox to search for an item I get this error:
The parameterized query '(#Parameter1 nvarchar(4000))SELECT * FROM
borrow where (Departme' expects the parameter '#Parameter1', which was
not supplied.
Can anyone help me?
If you pass null value to parameter,you will get this error even after you add the parameter
so try to check the value and if it null then use DBNull.Value
This will work
cmd.Parameters.Add("#Department", SqlDbType.VarChar)
If (TextBox2.Text = Nothing) Then
cmd.Parameters("#Department").Value = DBNull.Value
Else
cmd.Parameters("#Department").Value = TextBox2.Text
End If
This will convert the null values from the object layer to DBNull values that are acceptable to the database.
Your website is in serious danger of being hacked.
Read up on SQL Injection and how to prevent it in .NET
Your query problem is the least of your concerns right now.
But.....
#Misnomer's solution is close but not quite there:
Change your query to this:
cmd.CommandText = "SELECT * FROM borrow where (Department LIKE '%#DepartmentText%')"
and add parameters this way (or the way that #Misnomer does):
cmd.Parameters.AddWithValue("#DepartmentText",TextBox2.Text)
The important difference is that you need to change your CommandText.
Building on and simplifying ravidev's answer:
The VB.NET shorthand is:
cmd.Parameters.AddWithValue("#Department", IF(TextBox2.Text, DBNull.Value))
The C# shorthand is:
cmd.Parameters.AddWithValue("#Department", (object)TextBox2.Text ?? DBNull.Value)
Try adding parameters like this -
cmd.Parameters.Add("#Department", SqlDbType.VarChar)
cmd.Parameters("#Department").Value = TextBox2.Text
and change your command text to what #Abe Miessler does he is right i just thought you will figure it out.
If you are writing from a DataGridView control to your database, make sure there is no empty row. Set 'Allow User to add Rows' to false; it truncates the unnecessary last empty row.
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
//SelectCustomerById(int x);
comboBoxEx1.Items.Clear();
SqlCommand comm = new SqlCommand("spSelectCustomerByID", conn);
//comm.Parameters.Add(new SqlParameter("cust_name", cust_name));
//comm.CommandText = "spSelectCustomerByID";
comm.Parameters.Add(new SqlParameter("cust_id", SqlDbType.Int));
comm.CommandType = CommandType.StoredProcedure;
comm.ExecuteNonQuery();
SqlDataAdapter sdap = new SqlDataAdapter(comm);
DataSet dset = new DataSet();
sdap.Fill(dset, "cust_registrations");
if (dset.Tables["cust_registrations"].Rows.Count > 0)
{
comboBoxEx1.Items.Add("cust_registrations").ToString();
}
comboBoxEx1.DataSource = dset;
comboBoxEx1.DisplayMember = "cust_name";