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()"
Related
I am running an Access update query in VB.Net.
dbCustSpec_ADO.Execute("table_upt")
Ir runs fine except for the following "Update to" statement
[table].[field1] & [table].[field2]
The following is working properly
[table].[field1]
So does the following
[table].[field2]
It is only when I concatenate both fields when VB.Net throws an error:
System.Runtime.InteropServices.COMException: 'Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.'
Btw: The concatenation works properly when calling the query in Access.
My question is:
How can I concatenate both fields in order to make it run while calling it from VB.net
It not clear, are you using the .net oleDB provider here?
Or are you creating a instance of the Access database engine?
You better off to use oleDB such as this:
Imports System.Data.OleDb
And then your code to update can look like this:
Using conn As New OleDbConnection(My.Settings.TESTAce)
Dim strSQL As String = "UPDATE tblHotels SET FullName = FirstName + ', ' + LastName"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
cmdSQL.ExecuteNonQuery()
End Using
End Using
And if you wanted to ran a "existing" update query in Access?
They are considered store procedures. Say we have upate query saved in Access called
qryFirstLast
Then the above code to run that query would be:
Using conn As New OleDbConnection(My.Settings.TESTAce)
Dim strSQL As String = "qryFirstLast"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
cmdSQL.CommandType = CommandType.StoredProcedure
cmdSQL.ExecuteNonQuery()
End Using
End Using
Note how we set the command type = StoredProcedure.
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 am trying to retrieve a backup copy of the sql localdb through the environment of .net , but I get error .
the error : RESTORE cannot process database 'C:\Users\Emad-VB\Desktop\KizeN\KizeN\bin\Debug\Data\Data\DataStore.mdf' because it is in use by this session. It is recommended that the master database be used when performing this operation. RESTORE DATABASE is terminating abnormally.
the sql Query :
RESTORE DATABASE [C:\Users\Emad-VB\Desktop\KizeN\KizeN\bin\Debug\Data\Data\DataStore.mdf] FROM disk='C:\Users\Emad-VB\Desktop\bac\test.bac'
I tried again to use the database master to make restore but i get this error .
the error :
Incorrect syntax near 'Go'.
the sql Query :
use master
Go
RESTORE DATABASE [C:\Users\Emad-VB\Desktop\KizeN\KizeN\bin\Debug\Data\Data\DataStore.mdf] FROM disk='C:\Users\Emad-VB\Desktop\bac\test.bac'
This is the code that executes sql queries ....
Sub query(ByVal que As String)
'On Error Resume Next
Try
con = New SqlConnection(My.Settings.KConS)
If con.State = ConnectionState.Closed Then
con.Open()
End If
cmd = New SqlCommand
cmd.Connection = con
cmd.CommandType = CommandType.Text
Dim mm As String = " que"
cmd.CommandText = mm
cmd.ExecuteNonQuery()
If con.State = ConnectionState.Open Then
con.Close()
End If
Catch ex As Exception
End Try
End Sub
What is the solution to be able to retrieve the local database and Thanks
I see two problems:
"GO" is not a t-sql command. It is only meanigful to SQL utilities,
such as SQL Server Management Studio, so you shouldn't use it in
code that is being sent directly to the server.
I am not sure that you can change the databse within a connection by using "USE
MASTER". Instead you should create another connection string for
"master" and use it when you inititalize the connection that will perform the restore.
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
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