I'm writing some Excel VBA for a user to be able to insert records into a SQL Server table, using ADODB. This is working fine:
Dim conn As New ADODB.connection
conn.Open "<my connection string>"
Dim records As New ADODB.Recordset
records.CursorLocation = adUseClient
records.Open "SELECT TOP 1 * FROM [MyTable]", conn, adOpenStatic, adLockBatchOptimistic, adCmdText
' (Add some stuff here.)
records.UpdateBatch
Something's nagging me, though: is it possible to get the recordset pointed at the right table without doing a SELECT up front? This could get to be a pretty big table, so SELECT * FROM [MyTable] is out. I'm limiting that with a TOP 1, but I'm only doing a write, so it feels like I shouldn't have to do that!
The documentation makes it sound like you can just put a table name in the Source argument:
Use the optional Source argument to specify a data source using one of the following: a Command object variable, an SQL statement, a stored procedure, a table name, [...]
In practice, this doesn't work for me, and all of the following just error out with the message below, like it thinks I'm calling a stored procedure:
records.Open "MyTable", conn, ' [...]
records.Open "[MyTable]", conn, ' [...]
records.Open "[dbo].[MyTable]", conn, ' [...]
The request for procedure 'MyTable' failed because 'MyTable' is a table object.
Is there some syntax I'm missing here, or do I just have to go with the SELECT?
Related
I have a recordset and I want to copy this in new table in sql using VB Script. new table should be created as per recordset only. Someone has examples?
I know how to create new table but how to copy entire recordset to this table. I have something like following code and my recordset is retrieved in oRs variable.
Set oRs = CreateObject("ADODB.Recordset")
Set oCom = CreateObject("ADODB.Command")
oCom.CommandText = "my command text"
Set oRs = oCom.Execute
Kbv.
I have a table containing business priorities and the name of the query that is used to generate the results for each.
Is it possible to loop through this table and where it finds a query in the database with the same name, run it?
The closet thing I have found is below but I don't want to input my full query codes into a table.
http://www.experts-exchange.com/Database/MS_Access/Q_28284655.html
This will execute every query name that is in your table. It fills a recordset with the query names and then loops through and executes each one.
Dim sql As String
Dim rst As DAO.Recordset
Dim myQuery As String
sql = "Select myQuery from myTable"
Set rst = CurrentDb.OpenRecordset(sql)
Do While Not rst.BOF And rst.EOF
myQuery = rst(0)
DoCmd.OpenQuery myQuery, acViewNormal
rst.MoveNext
Loop
rst.Close
Set rst = Nothing
Let me know if you need to check to see if the query exists before you execute it. If so, I can add the code to search the querydefs collection for a query with the same name and only execute it if a match is found.
I can successfully create a pivot table in excel vba 2010 with the following code where the data come from an MS access database,
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\SQL.accdb"
rs.Open "SELECT * FROM Table1", con, adOpenStatic, adLockReadOnly
Set piv = ActiveWorkbook.PivotCaches.Create(xlExternal)
Set piv.Recordset = rs
piv.CreatePivotTable TableDestination:=Range("A1"), TableName:="P2"
con.Close
Set rs = Nothing
Set con = Nothing
But i when i change the SQL code of the recordset then the pivot can't be refreshed. In fact the pivot table has to be deleted and created over. Is there a way i can create a pivot table this way and refresh the data without deleting the pivot table.
The above answer was not quite what i was look for as different users would query from the database and will be using parameters as well, which could cause problems when multiple users query at the same time. But i did found a way to around my problem.
The code i placed above in my question, I can use to initially create my pivot and pull all the data through. I then build a separate Sub that can refresh the pivot table that looks as follows,
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\SQL.accdb"
rs.Open "SELECT * FROM Table1", con, adOpenStatic, adLockReadOnly
With Sheets(1).PivotTables("P2").PivotCache
Set .Recordset = rs
.Refresh
End With
Set rs = Nothing
con.Close
Set con = Nothing
A quick-fix, depending on how you usually update the SQL code, is as follows.
In ACCESS , create a query, using SQL mode as
SELECT * FROM Table1 and save it as Query1
In EXCEL, modify your code to SELECT * FROM Query1
That way, Excel will treat Query1 as a Table for all practical purposes and you may make Query1 in Access as complicated as you'd like, Excel will still pull up all its contents, keeping your code reusable.
I have 2 databases. In first one I have 10 tables. Second one is only 1 table. I would like to select 1 columns from each table from 1st database and Insert INTO another database. How can I manage this using INSERT INTO statement in VB.net?
I deleted my previous answer saying that you have to manually copy over the data. For now, let's assume you want to do this with a SELECT INTO statement.
The following code shows you how to execute a SQL command on your database using a ADO.NET connection and command object:
' Open a connection to your database (e.g. in a SQL Server): '
Using connection As IDbConnection = New SqlConnection("<Connection string>")
connection.Open()
Try
' Define the SQL command to be executed here: '
Dim command As IDbCommand = connection.CreateCommand()
command.CommandText = "SELECT <...> INTO <...>"
' Execute the command: '
command.ExecuteNonQuery()
Finally
connection.Close()
End Try
End Using
I hope this helps:
From sql side, you'll just need to write a stored procedure to insert into (ten) hash tables and select/insert them into your target table.
In Vb.net, you'll need: a connection object and a command object to call your stored procedure
How to check table is there or not?
Using VB 6.0
cmd.CommandText = "drop table t1"
cmd.Execute
Above code is working fine, but if table is not exist then it showing “table does not exit”
How to check table exist or table not exist?
Need VB CODE help?
If you just want to drop the table without throwing an error message, you can use the following SQL if you're using MySQL.
DROP TABLE t1 IF EXISTS
Other databases have a similar feature, but the syntax is different. To do the same in MSSQL:
IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 't1') DROP TABLE t1;
Although that looks very ugly.. there must be a better syntax to get the same result.
For a Jet MDB (and perhaps generically for many OLEDB Providers) you can use an approach like:
Private Sub Main()
Dim cnDB As ADODB.Connection
Set cnDB = New ADODB.Connection
cnDB.Open "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Jet OLEDB:Engine Type=5;Data Source='sample.mdb'"
'Check presence of table --------------
Dim rsSchema As ADODB.Recordset
Set rsSchema = _
cnDB.OpenSchema(adSchemaColumns, _
Array(Empty, Empty, "t1", Empty))
If rsSchema.BOF And rsSchema.EOF Then
MsgBox "Table does not exist"
Else
MsgBox "Table exists"
End If
rsSchema.Close
Set rsSchema = Nothing
'--------------------------------------
cnDB.Close
End Sub
You'd be better off checking for existence of the table concerned, rather than trying to drop it.
The SQL syntax is dependent on the database server/engine you're using, but for Sql Server you could use something like:
Sql Server 2000:
SELECT 1 as Exists FROM sysobjects WHERE name = 't1'
Sql Server 2005/2008:
SELECT 1 as Exists FROM sys.objects WHERE name = 't1'
You can then use VB like:
Dim rs as Recordset
Dim iExists as Integer
rs = cmd.Execute
On Error Goto DoesNotExist
rs.MoveFirst
iExists = CInt(rs!Exists)
DoesNotExist:
If iExists = 1 Then
' Put code here for if the table exists
Else
' Put code here for if the table does not exist
End If
Note: This code needs tidying up and "productionising" (i.e. I haven't actually tested that it works as I don't have VB6 on this machine)