I have some problems using a stored procedure in vb.net. I would like to know how to execute a stored procedure, e.g restore backup, by using the stored procedure itself and not its name.
Here is my code:
Try
con.ConnectionString = strCon
Dim strCommand as String = "RESTORE FILELISTONLY
FROM DISK = 'C:\AdventureWorks.BAK'
WITH FILE = 1
GO"
Dim cm As New SqlClient.SqlCommand(strCommand, con)
con.Open()
cm.ExecuteNonQuery()
When I execute it it says, cannot find stored procedure "RESTORE FILELIST ONLY ,...
So I would like to know if there is a way to execute stored procedure that I write within
visual basic itself as a string. Thanks.
Before
cm.ExecuteNonQuery()
try
cm.CommandType = CommandType.Text
Related
I am getting error while executing Postgresql(version 11) from VB.Net(2019)
I am executing a stored procedure from VB.NET 2019 on Postgresql 11. The error details are below.
Npgsql.PostgresException: '42809: spx_temp_to_ext() is a procedure'
The stored procedure is working correctly on Postgresql server and doesn't have any input parameters
Dim SQLCONN As New Npgsql.NpgsqlConnection
Dim SQLCMD As New Npgsql.NpgsqlCommand
SQLCONN.ConnectionString =
"SERVER=localhost;PORT=5432;DATABASE=xxxx;Uid=postgres;Password=xxxx"
SQLCMD.Connection = SQLCONN
SQLCMD.CommandType = CommandType.StoredProcedure
SQLCMD.CommandText = "spx_temp_to_ext"
SQLCONN.Open()
SQLCMD.ExecuteNonQuery()
SQLCONN.Close()
Getting error '42809: spx_temp_to_ext() is a procedure', although command type is defined as a stored procedure
Found the issue. By using commandtype as stored procedure, a select statement is automatically generated in VB.Net. To maintain backward compatibility, Postgresql stored procedures can't be called using select statements, we need to use Call method for that.
So it will be
command.text = "Call Stored_Procedure_Name()"
I want to delete all the contents of a MS Access table however I am not sure how to set up my SQL to do so.
So far I have found this online:
Dim SqlQuery As String = "DELETE * FROM QuestionResults WHERE Quizname = " & txtQuizName.Text & ";"
I have the connection to the database linked up due to my previous code, I am just unsure how to edit this code so that it deletes the contents of the table (i want it to delete every record, not the table itself)
Public provider As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
Public dataFile As String = "U:\My Documents\Visual Studio 2013\Projects\COMP4 Project\COMP4 Project\bin\Debug\QuizDatabase.accdb"
Public connString As String
Public myConnection As OleDbConnection = New OleDbConnection
Public dr As OleDbDataReader
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Simply DELETE FROM QuestionResults without a WHERE clause will delete every row.
The alternative command TRUNCATE TABLE QuestionResults will be faster, however I don't know if Access/JET supports the TRUNCATE statement or not.
Note that you must not generate SQL using string concatenation. Your program will break if someone puts "Baba O'Reilly" into your txtQuizName textbox. Instead use parameters.
What Dai said. Also you do not need an OleDbDataReaderuse an OleDbCommand:
Represents an SQL statement or stored procedure to execute against a data source.
Example use:
Dim command As New OleDbCommand(queryString, connection)
command.ExecuteNonQuery()
This seems so simple, but I can't resolve the error
Procedure or function 'test' expects parameter '#id', which was not supplied.
I have tried a dataadapter instead of the reader, tried the {call test (?)} syntax, and several variants on how to add the parameter.
CREATE PROCEDURE [dbo].test (#id int)
AS
BEGIN
select * from tmptable where id=#id
END
Using conn = New OdbcConnection(connstring)
conn.Open()
Dim cmd As OdbcCommand = New OdbcCommand("test", conn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#id", 6)
Dim reader As OdbcDataReader = cmd.ExecuteReader()
reader.Close()
conn.Close()
End Using
Try dropping the # - so AddWithValue("id",6) instead. I usually explicitly create the parameter and add it to the collection, and when I do I drop the # sign from the parameter name.
Also, I'll modify your code to look like how I usually use it and edit it into my post in a few minutes, if dropping the # doesn't work you can try my style, maybe there are some subtle differences.
EDIT: Oops, my bad, I use the explicitly defined parameters with SQLcommands, not ODBC commands! You can try leaving out the #, but I don't have a working example I can share with you, sorry :-(
EDIT 2: OK, I don't have an example, but Microsoft has one that looks a lot more like how I call my stored procedures using SQLCommands, see
http://msdn.microsoft.com/en-us/library/system.data.odbc.odbcparametercollection%28v=vs.90%29.aspx
Basically, I think your code would look like
Using conn = New OdbcConnection(connstring)
conn.Open()
Dim cmd As OdbcCommand = New OdbcCommand("{ call test(?) }", conn)
cmd.CommandType = CommandType.StoredProcedure
' replace this with the following cmd.Parameters.AddWithValue("#id", 6) '
Dim ParamID As New OdbcParameter()
ParamID.DbType = DbType.Int32
ParamID.Value = 6
cmd.Parameters.Add(ParamID)
' end replace '
Dim reader As OdbcDataReader = cmd.ExecuteReader()
reader.Close()
conn.Close()
End Using
And you should also be aware that some ODBC drivers are not good at getting recordsets back from stored procedures. I use SmallTalk to query DB2 through ODBC, and I can get a recordset back from a function, but not from a stored procedure. You may be encountering a similar limitation. What database are you using?
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.
Can A datatable somehow be passed into SQL Server 2005 or 2008 ?
I know the standard way seesm to be passing XML to a SP. And a datatable can easily be converted to XML somehow to do that.
What about passing a .NET object into a SP ? Is that possible ?
I remember hearing about SQL and CLR working together in 2008 somehow but I never understood.. Maybe that means you can refer to .NET objects within a Stored Procedure ?
You can create a User-defined table type in SQL. Then, in the stored procedure, accept a parameter of type (your user-defined table type) and pass in a datatable as it's value to a stored procedure.
Here's some examples from http://msdn.microsoft.com/en-us/library/bb675163.aspx:
In SQL:
CREATE TYPE dbo.CategoryTableType AS TABLE
( CategoryID int, CategoryName nvarchar(50) )
Then:
// Assumes connection is an open SqlConnection object.
using (connection)
{
// Create a DataTable with the modified rows.
DataTable addedCategories =
CategoriesDataTable.GetChanges(DataRowState.Added);
// Configure the SqlCommand and SqlParameter.
SqlCommand insertCommand = new SqlCommand(
"usp_InsertCategories", connection);
insertCommand.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
"#tvpNewCategories", addedCategories);
tvpParam.SqlDbType = SqlDbType.Structured;
// Execute the command.
insertCommand.ExecuteNonQuery();
}
Else you can choose SQl Bulk Insert.
I tried , most better way.
enter code here
Using dbConn As New SqlConnection(connectionStr)
dbConn.Open()
countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Using bulkcopy As SqlBulkCopy = New SqlBulkCopy(dbConn)
bulkcopy.DestinationTableName = "[dbo].[DocumentScan]"
Try
' Write from the source to the destination.
bulkcopy.WriteToServer(newDataTable)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Dim countEnd As Long = _
System.Convert.ToInt32(commandRowCount.ExecuteScalar())
End Using