Select a table where table name is stored in another table - sql

I have Access dba with a staging table where I store all table names.
Table name: SourceTable
tbl name field: SourceID
key field: ReferenceID
I would like to create SELECT query where "FROM table" is actually a dynamic table name based on SQL query. Something similar to this:
Select * from 'select SourceID from SourceTable where ReferenceID=1';

You might be able to do something with VBA to accomplish this.
Put a combobox that gets its items from your SourceTable on a form
Add a textfield on the form with your reference ID
Add a button on the form with the following On_Click code
Select the table name, enter your Reference ID, and click the button
Private Sub cmdQuery_Click()
Dim qdf As QueryDef 'Query definition containter'
Dim mySQL As String 'SQL Statement container'
Dim t As String 'table name containter'
Dim rid As String 'ReferenceID container'
'getting values for your table and ReferenceID'
t = cboTableNames.Value
rid = txtRID.Value
'building SQL string'
mySQL = "Select * from " & t & " WHERE ReferenceID=" & rid & ";"
'Delete the query if it already exists'
DoCmd.DeleteObject acQuery, "NewQuery"
'building query'
Set qdf = CurrentDb.CreateQueryDef("NewQuery", mySQL)
'running query'
DoCmd.OpenQuery qdf.Name
'closing query'
qdf.Close
'clearing memory'
Set qdf = Nothing
End Sub

Related

VBA to run specific queries

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.

Adding records to the table programatically

i am trying to append some records from a certain table to a new table ,
when i try it i am unable to append to the values
to the new table i.e "Table1" in this case what might be the reason for the data not getting appended to the table?
From what I can tell from your code you are just appending records from one table in your database into another table in the same database. You don't need to use a Recordset object to accomplish this; an INSERT INTO query will accomplish what you want.
Dim strSQL as String
Dim db as DAO.Database
Set db = CurrentDb
strSQL = "INSERT INTO Table1 ( UPI, COMPANY ) " & _
"SELECT INPUT_TBL.ID, INPUT_TBL.COMPANY FROM INPUT_TBL"
db.Execute strSQL, dbFailOnError
Set db = Nothing
Note that I used CurrentDb for the db object, under the assumption that the current database is the same one at C:\Users\test.accdb. If that's not the case, then you will need to do one of two things:
If you can add both of these tables as linked tables to the database you are running this code in, you can just use the same code as above. Instructions on how to add tables from an external database to your current database are available here: http://office.microsoft.com/en-us/access-help/import-or-link-to-data-in-another-access-database-HA001227658.aspx#BM3 and many other places on the internet.
If you can't add linked tables to your database for some reason, you can add IN clauses to the previous SQL string, which would become:
Dim strSQL as String
Dim db as DAO.Database
Dim dbname as String
Set db = CurrentDb
dbname = "C:\Users\test.accdb"
strSQL = "INSERT INTO Table1 ( UPI, COMPANY ) IN """ & dbname & """ " & _
"SELECT INPUT_TBL.ID, INPUT_TBL.COMPANY FROM INPUT_TBL IN """ & dbname & """"
db.Execute strSQL, dbFailOnError
Set db = Nothing
This code would allow you select the data from Table1 in the external database and add it to INPUT_TBL in the same external database.

Change data type of column in multiple tables in Access with VBA

I am fairly new to using VBA in MS Access and I am having trouble embedding SQL statements into VBA code. I have a database with almost 200 tables, and I would like to change the data type of one column (named lake) in each table to a "text" data type. I wrote the following code, but keep getting a syntax error for the ALTER TABLE statement.
Public Sub changeDataType()
Dim db As DAO.Database
Dim table As DAO.TableDef
Set db = CurrentDb
For Each table In db.TableDefs
DoCmd.RunSQL "ALTER TABLE" & table.Name & "ALTER COLUMN [lake] TEXT(100);"
Next
Set db = Nothing
End Sub
Can anyone tell me why I'm getting the syntax error?
Thanks,
Paul
this statement will not be correct:
DoCmd.RunSQL "ALTER TABLE" & table.Name & "ALTER COLUMN [lake] TEXT(100);"
if, for instance "table.Name" = "myTable", the resulting statement will look like this:
DoCmd.RunSQL "ALTER TABLEmyTableALTER COLUMN [lake] TEXT(100);"
try adding a space to separate the name, like this:
DoCmd.RunSQL "ALTER TABLE [" & table.Name & "] ALTER COLUMN [lake] TEXT(100);"

Insert multiple records in a single time using VBA Access

I am trying to avoid using multiple INSERT SQL queries but if I must I will. I have read over there that you can simply use INSERT INTO table(field) SELECT 'value' UNION ALL SELECT ... however I am having trouble with the syntax of it under MS Access 2007. I have tried a few variants but none works: I always get either "incorrect syntax" or "missing operator" error. I have tried with and without the ALL qualifier, with and without the SELECT keyword, etc. Here's how I am creating the query using VBA:
sql_query = "INSERT INTO " & tmp_tbl_name & " (transit)"
For Each xlCell In xlRange
sql_query = sql_query & " SELECT '" & xlCell.Value & "' "
sql_query = sql_query & "UNION"
Next xlCell
sql_query = Mid(sql_query, 1, Len(sql_query) - 6)
DoCmd.RunSQL (sql_query)
Here's a shortened sample of the query I am generating:
INSERT INTO tmp_tbl_2012_08_17_15_44_03 (transit)
SELECT 'L02_NA010001'
UNION
SELECT 'L13_PB010001'
UNION
SELECT 'L31_US020001'
UNION
SELECT 'L33_EX020010'
...
The table has only one VARCHAR(255) field and no relations to any other table (it's a temporary table to process a few things and keep only some elements of it).
Many thanks !
I think you can use good ol' DAO to do this rather quickly:
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("tmp_tbl_2012_08_17_15_44_03", dbOpenDynaset)
For Each xlCell In xlRange
With rs
.AddNew
.Fields("transit") = xlCell.Value
.Update
End With
Next xlCell
rs.Close
db.Close
It will probably be easier to run the statements one at a time in MS Access, the UNION will require FROM Table for each UNION statement, which means the FROM table will have to contain just one row, or a little fancy footwork.
INSERT INTO tmp_tbl_2012_08_17_15_44_03 (transit)
SELECT Transit FROM (
SELECT DISTINCT 'L02_NA010001' As Transit FROM tablename
UNION
SELECT DISTINCT 'L13_PB010001' As Transit FROM tablename
UNION ... )

How to check table exist or not exist

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)