Is there any SQL Statement procedure or code for optional requested field value? - sql

I'm a beginner. I created a database in vb.net and I need to build a query, in the SQL Statement - Table Adapter, which returns records even if parameters are NULL in one or more textbox. To be clear, I have several textboxes (related to fields) with which I can filter record results and I want to refine my research as much as I fill textboxes, reverse if I fill just one of them randomly.
Sorry if I confused you, but I guess you get it anyway.

In its simplest form (assuming SQL server param concepts)
-- Define your columns to pull back/display
select t1.column1, t1.column2, t1.column3...
-- Define the table, give it an alias if you're using more than one or it has a silly name
from thetable t1
-- Apply filters
where
-- For each textbox/column search combo, do this...
(column1 = #field1 or #field1 is null)
or -- If the filter is restrictive, use AND here
(column2 = #field2 or #field2 is null)
or -- If the filter is restrictive, use AND here
...

I would dump the table adapter for this requirement.
I am building the sql string using a StringBuilder. StringBuilder objects are mutable, String is not.
To run this Code
1. I assumed Sql Server. If this is not the case change all the data object (Connectio and Command) to the proper provider.
Add your connection string to the constructor of the connection.
Add your table name where it says "YourTable"
I just used TextBox1 etc. as control names. Use your actual control names
Replace Field1, Field2 etc. with your actual column names.
The parameter names (by convention, they start with #) can be anything you want as long as they match the name you add to the Parameters collection.
You will have to check your database for the actual datatypes of the fields. Be sure to convert the TextBox values to the compatible type. TextBox.Text is a string so it will be compatible to .VarChar but note number types or dates.
I added a Debug.Print to check what the Sql string looks like. Be cautious about where I have spaces when building the string. You can see the result in the immediate window (available from Debug menu).
If you don't already have a DataGridView on your form, add one so you can see the reults of your query.
Finally, always use parameters, use Using...End Using blocks, and open your connection at the last minute.
Private Sub RunDynamicQuery()
Dim sb As New StringBuilder
Dim AndNeeded As Boolean
Dim dt As New DataTable
Using cn As New SqlConnection("Your connection string")
Using cmd As New SqlCommand
sb.Append("Select * From YourTable Where ")
If Not String.IsNullOrEmpty(TextBox1.Text) OrElse Not String.IsNullOrWhiteSpace(TextBox1.Text) Then
sb.Append("Field1 = #Field1")
cmd.Parameters.Add("#Field1", SqlDbType.Int).Value = CInt(TextBox1.Text)
AndNeeded = True
End If
If Not String.IsNullOrEmpty(TextBox2.Text) OrElse Not String.IsNullOrWhiteSpace(TextBox2.Text) Then
If AndNeeded Then
sb.Append(" And")
End If
sb.Append(" Field2 = #Field2")
cmd.Parameters.Add("#Field2", SqlDbType.VarChar).Value = TextBox2.Text
AndNeeded = True
End If
If Not String.IsNullOrEmpty(TextBox3.Text) OrElse Not String.IsNullOrWhiteSpace(TextBox3.Text) Then
If AndNeeded Then
sb.Append(" And")
End If
sb.Append(" Field3 = #Field3")
cmd.Parameters.Add("#Field3", SqlDbType.VarChar).Value = TextBox3.Text
AndNeeded = True
End If
sb.Append(";")
cmd.Connection = cn
Debug.Print(sb.ToString)
cmd.CommandText = sb.ToString
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dt
End Sub

Related

How do I retrieve a value from an SQL query and store it in a variable in VB.NET?

I am trying to find the max product ID and store the value in a local variable "MaxID" and return this value. I am trying to convert the result of the query into an Integer type but I am not able to do it. Below is the code:
Public Function GetMaxID(ByVal TableName As String, ByVal ID As String) As Integer
Dim MaxID As Integer
Dim sqlquery As SqlCommand
Dim field_name As String = ID
Dim con As SqlConnection
con = New SqlConnection()
con.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='D:\Docs Dump\Work\Srinath\SrinathDB.mdf';Integrated Security=True;Connect Timeout=30"
con.Open()
Try
sqlquery = New SqlCommand("SELECT MAX( #field ) FROM #table ", con)
sqlquery.Parameters.AddWithValue("#field", field_name)
sqlquery.Parameters.AddWithValue("#table", TableName)
MaxID = CInt(sqlquery.ToString)
con.Close()
Return MaxID
Catch ex As Exception
Return 0
Exit Function
con.Close()
End Try
End Function
End Class
MaxID = CInt(sqlquery.ExecuteScalar())
You also should know about SqlCommand.ExecuteReader(), SqlCommand.ExecuteNonQuery() (for inserts/updates/deletes), and SqlDataAdapter.Fill().
Where you'll still have a problem is you can't use a parameter value for the table name or column name. The Sql Server engine has a "compile" step, where it has to be able to work out an execution plan, including permissions/security, at the beginning of the query, but variable names like #table and #field aren't resolved until later. It's not what actually happens, but think of it as if you had string literals in those places; imagine trying to run this:
SELECT MAX('ID') FROM 'MyTable'
MAX('ID') will always return the string value ID, and not anything from an ID column in any rows. But the MyTable part is not the correct place for a string literal, and such a query wouldn't even compile.
I also see people here from time to time try to create functions like GetMaxId(), and it's almost always misguided in the first place. If the intended use for this function is the same as what I usually see, you're setting up a major race condition issue in your application (one that probably won't show up in any testing, too). Sql Server gives you features like identity columns, sequences, and the scope_identity() function. You should be using those in such a way that new IDs are resolved on the server as they are created, and only (and immediately) then returned to your application code.
But that issue aside, here's a better way to structure this function:
Public Class DB
Private conString As String = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='D:\Docs Dump\Work\Srinath\SrinathDB.mdf';Integrated Security=True;Connect Timeout=30"
'You want a separate method per-table that already knows the table and column names
Public Function GetMyTableMaxID() As Integer
Dim sql As String = "SELECT MAX(ID) FROM MyTable"
Using con As New SqlConnection(conString), _
sqlQuery As New SqlCommand(sql, con)
'Parameters would go here.
'Do NOT use AddWithValue()! It creates performance issues.
' Instead, use an Add() overload where you provide specific type information.
'No exception handling at this level. The UI or business layers are more equipped to deal with them
con.Open()
Return CInt(sqlQuery.ExecuteScalar())
End Using
'No need to call con.Close()
'It was completely missed in the old code, but handled by the Using block here
End Function
End Class

Can't generate a StockID above 10

This is the code that tries to grab the largest StockID from the database (Access database) , but my problem is that it generates StockID's up to "S10", after this it simply doesn't increment any further. This is the subroutine that generates the StockID:
Sub generate_Stock_ID()
Dim Stock_start As String = "S"
Dim Stock_Gen As String = "SELECT MAX(StockID) FROM tblStock WHERE StockID LIKE '" & Stock_start & "%%%' "
Dim da As OleDbDataAdapter = New OleDbDataAdapter(Stock_Gen, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "StockID")
Dim dt As DataTable = ds.Tables("StockID")
Dim count As Integer = ds.Tables("StockID").Rows.Count
If ds.Tables("StockID").rows.count = 0 Then
StockID = "S1"
Else
StockID = ds.Tables("StockID").Rows(0).Item(0)
StockID = StockID.Substring(1, (StockID.Length - 1))
StockID = Stock_start & (StockID + 1)
End If
End Sub
Screenshot of my database
Note* there are multiple ID's for various other subroutines which all share the same incrementation issue, so if i fix this i fix the other ones too. So at the moment i think my problem lies in the syntax of my SQL statement, but im open to suggestions.
Thanks!
Don't treat an Integer as String. Otherwese MAX or ORDER BY will use lexicographical instead of numerical order which means that S11 is "lower" than S2.
So you should make this column an int-column and prepend S only where you display it. Then MAX(StockID) returns an Integer, you just have to cast it and add 1:
Using conn As New OleDbConnection("Connection-String")
Using cmd As New OleDbCommand(Stock_Gen, conn)
conn.Open()
Dim stockIDObj As Object = cmd.ExecuteScalar()
If stockIDObj IsNot Nothing Then
Dim maxStockId As Int32 = DirectCast(stockIDObj, Int32)
maxStockId += 1
' ...... '
End If
End Using
End Using
You should also change OPTION STRICT to ON. Then this would never compile since the same variable cannot be used for an Object, String and Integer which is very good since it prevents errors.
If you want to keep it as string you have to cast the substring always in the database which is less readable and less efficient. I also don't know how to do it in access.
If you want to change the type of column in an already populated table you should first add a new column with a similar name which is of type int. If all have S at the beginning you could first remove that, then you can update the new column with the casted int value. Finally you can delete the old column and rename the new to the old.
The root of this issue that StockID is a STRING and 'S1'>'S10' so for all StockId > 10 you get max = 'S1'.
As a fast fix try to change MAX(StockID) to:
SELECT 'S'+CAST(MAX(CAST(SUBSTRING(StockID,2,100) as int)) as varchar(100))
For ACCESS DB try to use:
SELECT "S" & cstr(MAX(CINT(MID(StockID,2,100))))

VB.NET Multiple Selects at once using SQL Server CE

I have an array list which contains ids for some items. I would like to perform a multiple select at once from a SQL Server CE database and using my array list which contains what items id to be selected, something similar when doing for example multiple update in oracle (ODP.NET) as explained here: Oracle bulk updates using ODP.NET
where you can pass an array as a parameter.
I would like to do the same but for a multiple select instead in case of SQL Server CE. Is it possible?
DRAFT about what I would like to do:
SqlCeCommand = SqlCeConnection.CreateCommand()
SqlCeCommand.CommandText = "SELECT * FROM MyTable WHERE Id=:ids"
SqlCeCommand.CommandType = CommandType.Text
SqlCeCommand.Parameters.Add(":ids", DbType.Int32, ArrayListOfIds, ParameterDirection.Input)
Using reader As System.Data.SqlServerCe.SqlCeDataReader = SqlCeCommand.ExecuteReader()
Using targetDb As Oracle.DataAccess.Client.OracleBulkCopy = New Oracle.DataAccess.Client.OracleBulkCopy(con.ConnectionString)
targetDb.DestinationTableName = "MyTable"
targetDb.BatchSize = 100
targetDb.NotifyAfter = 100
targetDb.BulkCopyOptions = Oracle.DataAccess.Client.OracleBulkCopyOptions.UseInternalTransaction
AddHandler targetDb.OracleRowsCopied, AddressOf OnOracleRowsCopied targetDb.WriteToServer(reader)
targetDb.Close()
End Using
reader.Close()
End Using
You should try this approach by constructing your "IN" clause and adding each parameter in a for each loop:
SqlCeCommand = SqlCeConnection.CreateCommand()
SqlCeCommand.CommandType = CommandType.Text
Dim sb As New StringBuilder()
Dim i As Integer = 1
For Each id As Integer In ArrayListOfIds
' IN clause
sb.Append("#Id" & i.ToString() & ",")
' parameter
SqlCeCommand.Parameters.Add("#Id" & i.ToString(), DbType.Int32, id, ParameterDirection.Input)
i += 1
Next
If you're calling a Stored Procedure, you can do this:
Serialize the array to a string of XML, like this: https://stackoverflow.com/a/6937351/734914
Call the stored procedure, passing in the string parameter
Parse the string of XML into a local table variable containing the ID's, like this: https://stackoverflow.com/a/8046830/734914
Execute whatever queries you need to using the ID's
The links that I referenced might not be the best examples on the web, but the concept of "serialize to XML, pass string parameter, deserialize XML" should work here

Sorting numbers in Access and .NET

I have an Access table which has a Number field and a Text field.
I can run a query like this:
SELECT * FROM Table ORDER BY intID ASC
//outputs 1,2,3,10
But when I try to run the same query through the .NET OleDB client, like this:
Private Sub GetData()
Using cnDB As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Path)
cnDB.Open()
Dim SQL As String = "SELECT * FROM Table ORDER BY intID ASC"
Dim cmd As New OleDbCommand(SQL, cnDB)
Dim dr As OleDbDataReader = cmd.ExecuteReader()
While dr.Read()
lst.Items.Add(dr.Item("intID") & " - " & dr.Item("strName"))
End While
cnDB.Close()
End Using
End Sub
I get items in the order 1,10,2,3.
What's going on here, and how can I have the data sort "naturally" (1,2,3,10) in both places?
try
SELECT * FROM Table ORDER BY CInt(intID) ASC
to explicitly tell Access to treat this as an integer and not a string. Obviously, something in the OleDbClient is seeing this field as a string (text field) and sorting accordingly.
I suspect the problem is your connection string. If you're connecting to an Access database and include IMEX=1 in your connection string, the provider will treat all data as string. As such, the ordering will order by the string value, giving you 1, 10, 2, 3, as opposed to leaving the intID as an integer, and ordering it in numerical order.
It looks like you're getting a lexical (alphabetic) order. This will be correct if something in your database or query thinks that is a varchar/text column type instead of a numeric type.

how to get data to textbox from the database

I have a form with one combo box and text box, and an SQL database
named balance with two columns; one as customername and the other as obbalance.
I had bound all of the customer name to the combo box, now what I have to do is,
when a user selects a customer name from the combo box, the text box should show the obbalance of the selected customername; here, the customer name will not be repeated - only one name per customer.
What can I do? Please help me.
Dim conectionstring As String
conectionstring = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True"
Dim ST As String = ComboBox1.SelectedText
Dim sqlcon As New SqlConnection(conectionstring)
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = " & " '" & ST & "'" & "", sqlcon)
MessageBox.Show(TextBox1.Text)
Dim result As Object
Try
sqlcon.Open()
' Dim sdr As SqlDataReader = sqlcmd.ExecuteReader()
result = sqlcmd.ExecuteScalar()
If result IsNot Nothing Then
TextBox1.Text = result.ToString()
MessageBox.Show(TextBox1.Text)
End If
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
I've tried this, but I can't see the value in the text box, and obbalance is a floating-point value from the SQL database.
If you're updating a text box, is this a single result (scalar value)? If so, the first thing I'd do is use ExecuteScalar not ExecuteReader. Then, use debug mode with breakpoints to get a better idea of what is actually happening. It may simply be that you're not getting any results.
Note: I'm assuming the bad coding practice (in-line sql statement, hard-coded connection string, etc.) are for clarity. If they're not, fix them.
Make the follwing changes:
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = '" & ST & "'", sqlcon)
TextBox1.Text = sdr.GetString(yourColumnIndex)
ComboBox1.SelectedText returns the highlighted (selected) text on the ComboBoxControl. That will be empty if you haven't use your mouse to select a portion of its text or hold the shift while you are pressing the direction keys on your keyboard. And that's probably why your query returns ZERO RECORDS.
Use the following instead:
Dim ST As String = ComboBox1.SelectedItem.Text
Set a breakpoint and ensure you are getting the value for OBBALANCE (see if you are getting any rows period might be good). Also, make sure you can only get one row, as you are iterating forward, even when you only need one value.
Better yet, consider ExecuteScalar, which only returns a single value. While you are at it, parameterize the SQL query so you don't get SQL injected.
UPDATE: Just change it here:
sdr = sqlcmd.ExecuteReader()
to something like
Dim s as String = sqlcmd.ExecuteScalar()
Then use s as your textbox value. You may have to ToString() the value or otherwise cast as string, as I believe the ExecuteScalar() returns an object.