Running a SQL Server stored proecdure with OPENROWSET in VB.Net - sql

I am trying to automatically import tables from an excel sheet into a table in an SQL database via VB.net. So far I have done the following:
I created a stored procedure in the database which imports the table via openrowset:
CREATE PROCEDURE ImportTable
AS
SET NOCOUNT ON;
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
SELECT *
INTO [Table]
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=C:\ExcelFile.xlsm', Table$);
GO
Once created this procedure works perfectly when executed in SSMS.
I then wrote a script in VB.net to run the stored procedure with the same login details:
Dim ConnectionString As String
Dim sqlCon As SqlConnection
' Open a database connection and use it to run the stored procedure
ConnectionString = "Data Source=ServerName;" &
"Initial Catalog=DBName;" &
"User=UserName;" &
"Password=Password;" &
"Integrated Security=SSPI;"
sqlCon = New SqlConnection(ConnectionString)
Using (sqlCon)
Dim sqlComm As New SqlCommand
sqlComm.Connection = sqlCon
sqlComm.CommandText = "ImportTable"
sqlComm.CommandType = CommandType.StoredProcedure
sqlCon.Open()
sqlComm.ExecuteNonQuery()
End Using
However when I try to run the SP in VB.net (or VB excel) I get the following error:
System.Data.SqlClient.SqlException: 'Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Unspecified error".'
I have looked around and found multiple threads on getting this to work in SSMS, but no solutions for a situation where it runs fine in SSMS but not in VB.net.
Any idea why the SP wont run through a method external to SSMS?
Craig

First Make sure the Excel file isn't open.
Then you need to check whether you have installed the 2007 Office System Driver: Data Connectivity Components which is necessary for Microsoft OLEDB ACE 12.0 driver to work.
or you can
USE [master]
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO
Nice Link

Related

VB.NET error while executing Postgresql stored procedure

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()"

how to export sql table data into excel worksheet?

I have this table that I want to export its data into my excel file.
so far I've tried every topic here but nothing worked.
I've tried these 2:
insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=D:\excel\testing.xls;',
'SELECT * FROM [newStart$]') select * from OutputResult
insert into OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 8.0;Database=D:\excel\testing.xls;',
'SELECT * FROM [newStart$]') select * from OutputResult
when I run it with jet I'll get this error:
OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)" returned message "The Microsoft Jet database engine could not find the object 'newStart$'. Make sure the object exists and that you spell its name and the path name correctly.".
Msg 7350, Level 16, State 2, Line 1 Cannot get the column information from OLE DB provider "Microsoft.Jet.OLEDB.4.0" for linked server "(null)".
and when I ran the ACE.OLEDB I get this one:
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "The Microsoft Office Access database engine could not find the object 'newStart$'. Make sure the object exists and that you spell its name and the path name correctly.".
Msg 7350, Level 16, State 2, Line 1
Cannot get the column information from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
I give my sql account full control permission as well.
plus I run these two as well:
USE [master]
GO
EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'AllowInProcess' , 1
GO
EXEC master . dbo. sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0' , N'DynamicParameters' , 1
GO
2:
sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
I would appreciate it if anyone could point me into the right direction.
strSqlQry = "Place SQL Qry Here"
vFilePath = "Database Path"
'Create Objects
Set conn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
'Open Connection
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & vFilePath & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes;"";"
'Execute Qry
rs.Open strSqlQry, conn, adOpenStatic, adLockOptimistic
'Place recorset into excel worksheet
ActiveSheet.Range("A1").CopyFromRecordset (NewRS)
rs.Close
Set rs = Nothing
Set conn = Nothing
You can use way written in this topic How do you transfer or export SQL Server 2005 data to Excel
In excel using External data menu connect to database

The microsoft access database engine cannot find the input table or query 'dbo'.. (VBA, Access2010)

Helllo!
I'm an MS Access-beginner. After an upgrade from Access2003 to Access2010 I am changing the database connection of our MS Access-Application from ODBCDirect (not supported anymore) to ADODB.
After (hopefully) successfully establishing a DB connection over an ADODB.Connection object I am initializing an ADODB.Command object:
Dim qdfWork As ADODB.Command
...
Set qdfWork = New ADODB.Command
Set qdfWork.ActiveConnection = CurrentProject.Connection
qdfWork.CommandText = "[dbo].[storedProcedureName]"
qdfWork.CommandType = adCmdStoredProc
qdfWork.Parameters.Refresh 'HERE THE ERROR-MESSAGE OCCURS
...
There is a stored procedure with the exactly same name "[dbo].[storedProcedureName]" stored on the server, but I still get the error-message:
"the microsoft access database engine cannot find the input table or query 'dbo'. Make sure it exists and that its name is spelled correctly."
If I don't write "[dbo]" in the CommandText I still get the same message, telling that "[storedProcedureName]" can't be found.
Here is my ADODB.Connection.connectionString:
"Driver={Microsoft Access Driver (*.mdb)};Dbq=\\folder1\folder2\User1\Database.mdb; Uid=Admin;Pwd=password;"
The connection via this connectionString works fine I think, I don't get any error-messages when connecting to the DB.
I checked that CurrentProject.Connection is really the connection I need.
I don't understand why my Application can't find this stored procedure although it is stored on the server.
Thanks for reading

Database connection error with MSSQL 2005

I've got the following code and I'm trying to establish a connection to a data base. I have MSSQL 2005 as the database and trying to connect though ODBC connection.
Importantly I'm trying to use 'Windows authentication' instead of 'SQL authentication' to login to the database. (Note that SQL auth is NOT an option for me!)
<%
Dim Conn
Set Conn = CreateObject("ADODB.Connection")
Dim ConnectionString
Conn.ConnectionString = "Server= CLMSAWN002; Database= mohan_db; Integrated Security=True;"
Conn.Open ConnectionString
Conn.CommandTimeout=120
Sub CloseConn
Conn.Close
Set Conn = Nothing
End Sub
%>
In the live environment I get the following error.
Microsoft OLE DB Service Components error '80040e21'
Multiple-step OLE DB operation generated errors. Check each OLE DB
status value, if available. No work was done.
/CustomerMarketing/_db.asp, line 10
Can you help me understand what cause this and a possible solution?

restore sql localdb with vb.net

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.