SQLCommand causing duplicate Stored Proc executions - sql

I got an issue that I am completely stumped on.
Part of my application calls a Stored Proc using SQLConnection/SQLCommand. I'm hitting a SQL 2005 database and I am able to make the connection and execute the SP just fine. The problem is it periodically executes the SP multiple times; some times twice, some times three times.
This is basically how I execute the SP...
Dim conString As String = "<Typical Connection String>"
Dim cn As SqlConnection = new SqlConnection(conString)
Dim cmd As SqlCommand = New SqlCommand("dbo.JobStoredProc", cn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#Val", SqlDbType.VarChar, 12).Value = "Test Value"
cn.Open()
Dim queryResult As Integer = cmd.ExecuteNonQuery
cn.Close()
cn.Dispose()
I can't figure out why sometimes it executes only once, but other times it executes multiple times. Is there something I'm missing? Is there a better way to go about executing the SP?
Thank you very much in advance!

As it turns out it was because I had two of the same File Watchers looking at the same directory. This was causing the above function to fire twice at the exact same time.

Related

Cant save or update my SQL Server tables using vb.net

I am a complete beginner to .net and am confused at some basic things. Please help.
First of all the table I create and populate (by right clicking tables in server explorer) disappear once I restart the computer. how do I keep them.
Is there any better place/interface to type SQL queries in vb.net than the command prompt.
In the following code:
Dim cn As SqlConnection = New SqlConnection(strConnection)
cn.Open( )
' Create a data adapter object and set its SELECT command.
Dim strSelect As String = _
"SELECT * FROM Categories"
Dim da As SqlDataAdapter = New SqlDataAdapter(strSelect, cn)
' Load a data set.
Dim ds As DataSet = New DataSet( )
da.Fill(ds, "Categories")
This far the code runs fine but just to gain better understanding, I would like to ask that
while data from SQL Server database was saved into da in accordance to the query, why do we need to save/transfer it in the dataset object ds.
Is there any additional benefit of SqlCommand over SqlDataAdapter besides speed?
Dim autogen As New SqlCommandBuilder(da)
Dim dt As DataTable = ds.Tables("Categories")
' Modify one of the records.
Dim row As DataRow = dt.Select("CategoryName = 'Dairy Products'")(0)
row("Description") = "Milk and stuff"
gives an error when I use it with
da.Update(ds, "Categories")
regarding dt.select not returning any value.
What is the way out?
to answer your questions :
The tables you create with the server explorer are IN MEMORY. Same goes for dataset, they are in-memory representation of your table. As for your 2nd example, the DS you use isnt filled when you try to get the DT. hence why the DT is empty.
If your starting, I would suggest you go look into Linq-to-Sql (http://msdn.microsoft.com/en-us/library/bb425822.aspx) for a more up-to-date way of doing sql in .net ( I think its 4.0 framework)
As for the 2nd point, I'd say normally you should use store procedure for most of your sql commands .. the sqlcommand is use like this
Try
Cmd = New SqlClient.SqlCommand("st_InventoryStatus_Or_AnyStoreProcName_Or_ASqlQuery")
Cmd.CommandTimeout = 300 'not really needed'
Cmd.CommandType = CommandType.StoredProcedure 'you can type CommandType.Text here to use directly your "Select * from Category"'
Cmd.Parameters.Clear() 'just to be sure its empty, its not mandatory'
Cmd.Parameters.Add("#idCategory", SqlDbType.Int).Value = myCategory.Id 'here are the parameters of your store proc, or of your query ("select * from Category where Category.id = #Id")'
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Information)
End Try

SQL Stored Procedure VB.Net

I have a Stored Procedure which when run on SQLServer takes 1 second to run, yet in my VB.Net code it takes nearly 20 seconds. It takes a long time on the line:
Adapter.Fill(ds,"TimeTable")
Am I doing something wrong for it to take so long?
My code snippet is below:
SQLConn = New SqlConnection(SQLDConnString)
cmd = New SqlCommand("SPNAME", SQLConn)
cmd.CommandType = CommandType.StoredProcedure
SQLConn.Open()
cmd.Parameters.AddWithValue("#p1", p1)
cmd.Parameters.AddWithValue("#p2", p2)
cmd.Parameters.AddWithValue("#p3", p3)
cmd.Parameters.AddWithValue("#p4", p4)
adapter.SelectCommand = cmd
adapter.Fill(ds, "TimeTable")
DataGridView1.DataSource = ds.Tables("TimeTable")
SQLConn.Close()
If your datagridview property for column and row height/width is set to auto, it can take a lot of time to finish the procedure. I had this happen once, where a stored procedure took an abnormally large amount of time and it ended up being that property that was causing it to stall.
I seemed to find a fix to this by declaring local variables in my SP and then assigning my Parameters to these variables.
Something to do with parameter sniffing.

External database path as parameter for parametrized query to Access

I'm writing small VB.Net app which should build reports based on data gathered from some external MDB-files (Access 2007). It was planned that this app will use parametrized SQL queries to collect data. One of the parameters for these queries is path to the external MDB-file.
Here goes sample code:
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=C:\Temp\Temp.mdb;")
conn.Open()
Dim cmd As New OleDbCommand()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT * INTO Trend FROM TI IN '?' WHERE TI.Id=?;"
With cmd.Parameters
.Add("#p1", OleDbType.VarChar).Value = "C:\Temp\Source.mdb"
.Add("#p2", OleDbType.Integer).Value = 5
End With
cmd.ExecuteNonQuery()
conn.Close()
Looks simple but it doesn't works. After launch my app throws following exception - System.Data.OleDb.OleDbException: Disk or network error.
Have spent a whole day to make it work with no success. What have I done wrong?
This is a comment that others have suggested is the answer to the question:
Nothing in an Access/Jet/ACE FROM clause is parameterizable (unless it's inside a subquery, of course).
With Access/Jet/ACE your only choice is to use some other method to write the FROM clause on-the-fly.

Perform Action on Each Record from SQLDataSource

I've submitted a bunch of questions as of late - but this has been a great repository of information. I'm a .NET nub, as you can see, so if I'm missing basics or information please let me know and I'll try and fill in the gaps.
I'm using ASP.NET/VB.NET to create this with SQL 2005. I have a project where I'd like to take a set of records from a table, then send each one through an API, get a result and writeback the result to a table, then move to the next.
Initially, my thought was create a SQLDataSource that grabs all the records, then perform the action on a button to do the action of sending through each record.
Is there a way I can call the recordset from SQLDataSource and perform a loop? I'm thinking something like in Classic ASP/VBScript where you would open a RecordSet, do an action, then Loop until the RS was EoF.
Thanks for the help!
You can may want to put your results in a dataset. After getting the results, you can loop through the returned rows
Dim ds As Dataset = GetSomeDataFromSq
For Each dr As DataRow In ds.Tables(0).Rows
Console.WriteLine (dr("ColName"))
Next
You could also use a sqlDataReader
Using conn As sqlconnection = New sqlconnection("put conn info")
Using MyCommand As SqlCommand = New SqlCommand("SELECT ProductName FROM products", conn)
conn.Open()
Using myDataREader As SqlDataReader = MyCommand.ExecuteReader
While myDataREader.Read
Response.Write("Name: " & myDataREader.Item("ProductName"))
End While
End Using
End Using
End Using

Jet Database (ms access) ExecuteNonQuery - Can I make it faster?

I have this generic routine that I wrote that takes a list of sql strings and executes them against the database. Is there any way I can make this work faster? Typically it'll see maybe 200 inserts or deletes or updates at a time. Sometimes there is a mixture of updates, inserts and deletes. Would it be a good idea to separate the queries by type (i.e. group inserts together, then updates and then deletes)?
I am running this against an ms access database and using vb.net 2005.
Public Function ExecuteNonQuery(ByVal sql As List(Of String), ByVal dbConnection as String) As Integer
If sql Is Nothing OrElse sql.Count = 0 Then Return 0
Dim recordCount As Integer = 0
Using connection As New OleDb.OleDbConnection(dbConnection)
connection.Open()
Dim transaction As OleDb.OleDbTransaction = connection.BeginTransaction()
'Using cmd As New OleDb.OleDbCommand()
Using cmd As OleDb.OleDbCommand = connection.CreateCommand
cmd.Connection = connection
cmd.Transaction = transaction
For Each s As String In sql
If Not String.IsNullOrEmpty(s) Then
cmd.CommandText = s
recordCount += cmd.ExecuteNonQuery()
End If
Next
transaction.Commit()
End Using
End Using
Return recordCount
End Function
You can use a data adapter to update the whole dataset at once. It will be faster to run the queries on the ADO object than the database directly. After the batch has cycled, update the whole dataset. That might be faster, but will require some extra coding up front and overhead on the application.