Splitting NoName column in SQL Query - sql

I want to use a CSV file Test1.csv to create a Recordset with customized column names.
The CSV file format:
(Blank) | SomeAggr | (Blank) | Div1 | Div2 | Div3
-----------------------------------------------------------
G0.1 | 1.23 | | ABC | DEF | GHI
G0.2 | 2.45 | | JKL | MNO | PQR
G0.3 | 9.02 | | STU | VWX | YZA
G1.1 | 3.32 | | ZYX | WVU | TSR
G1.2 | 5.53 | | QPO | NML | KJI
G1.3 | 1.15 | | HGF | EDC | BAZ
G1.4 | 4.65 | | FKJ | OTU | WKL
The 1st & 3rd Columns have blank headers. The 1st column contains data I want to split it into two columns as shown in SQL Query.
Note - I am creating a recordset and do not want to do any transformations using a WorkSheet.
The final Recordset via SQL Query should look like this:
GVal | Pos | Aggr | (Blank) | DV A | DV B | DV C
--------------------------------------------------------------------
0 | 1 | 1.23 | | ABC | DEF | GHI
0 | 2 | 2.45 | | JKL | MNO | PQR
0 | 3 | 9.02 | | STU | VWX | YZA
1 | 1 | 3.32 | | ZYX | WVU | TSR
1 | 2 | 5.53 | | QPO | NML | KJI
1 | 3 | 1.15 | | HGF | EDC | BAZ
1 | 4 | 4.65 | | FKJ | OTU | WKL
I am running the following code:
Option Explicit
Sub Testing()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim strDataSource$, strF1$, strFF1$, strSql$, oCon as Object, oRs as Object, i%, Fld
strFF1 = "Test1.csv"
strF1 = "`C:\Users\adam\Downloads\Test Folder`\"
strDataSource = Thisworkbook.Path
Set oCon = CreateObject("ADODB.Connection")
Set oRs = CreateObject("ADODB.Recordset")
strCon = "Driver=Microsoft Access Text Driver (*.txt, *.csv);Dbq=" & strDataSource & ";Extensions=asc,csv,tab,txt;HDR=Yes;"
'Getting Top 1 row to loop through fields and create SQL string accordingly.
strSql = "SELECT TOP 1 * FROM " & strF1 & strFF1
oCon.Open strCon
Set oRs = oCon.Execute(strSql)
i = 1
strSql = "SELECT "
For Each Fld In oRs.Fields
Select Case True
Case Is = Fld.Name = "NoName" '1st NoName column
If Fld.Value <> vbNullString Then
strSql = strSql & "CLng(Replace(Left(" & Fld.Name & ", InStr(" & Fld.Name & ", ""."") - 1), ""G"", """"))" & " AS [GVal], "
strSql = strSql & "CLng(Right(" & Fld.Name & ", Len(" & Fld.Name & ") - InStr(" & Fld.Name & ", ""."")))" & " AS [Pos], "
Else
strSql = strSql & Fld.Name & ", " '2nd NoName column
End If
Case Is = Fld.Name = "SomeAggr"
strSql = strSql & "[" & Fld.Name & "] AS [Aggr],"
Case Is = InStr(1, Fld.Name, "Div") > 0
strSql = strSql & "[" & Fld.Name & "] AS [DV " & Chr(i + 64) & "], "
i = i + 1
End Select
Next Fld
If Right(Trim(strSql), 1) = "," Then strSql = Left(Trim(strSql), Len(Trim(strSql)) - 1)
strSql = strSql & " FROM " & strF1 & strFF1
oRs.Close
' >>> getting error on below `Set oRs` line
[Microsoft][ODBC Text Driver] '' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.
Set oRs = oCon.Execute(strSql)
Stop
ExitSub:
oRs.Close
oCon.Close
Set oRs = Nothing
Set oCon = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
ErrorHandler:
MsgBox "Error No: " & Err.Number & vbCrLf & "Description: " & Err.Description, vbCritical + vbOKOnly, "An Error occurred!"
Err.Clear
On Error GoTo 0
Resume ExitSub
End Sub
Here is the SQL Query.
SELECT CLng(Replace(Left(NoName, InStr(NoName,".")-1), "G", "")) AS [GVal],
CLng(Right(NoName, Len(NoName) - InStr(NoName,"."))) AS [Pos],
[SomeAggr] AS [Aggr],
[Div1] AS [DV A],
[Div2] AS [DV B],
[Div3] AS [DV C]
FROM `\C:\Users\Adam\Downloads\Test Folder`\Test1.csv
The code gives me the following error:
[Microsoft][ODBC Text Driver] '' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.
I don't know how to get a reference or select the 1st Blank Column to split it's values into two columns.
The Query works in MSAccess and the 1st NoName column is shown as Field1 and 2nd NoName column is shown as Field3.

SQL code expects single quotes as string deliminators instead of double quotes. In the For Each Fld In oRs.Fields loop, there are two lines which use double quotes instead of single quotes while constructing strSql:
strSql = strSql & "CLng(Replace(Left(" & Fld.Name & ", InStr(" & Fld.Name & ", ""."") - 1), ""G"", """"))" & " AS [GVal], "
strSql = strSql & "CLng(Right(" & Fld.Name & ", Len(" & Fld.Name & ") - InStr(" & Fld.Name & ", ""."")))" & " AS [Pos], "
These should be changed to:
strSql = strSql & "CLng(Replace(Left(" & Fld.Name & ", InStr(" & Fld.Name & ", '.') - 1), 'G', ''))" & " AS [GVal], "
strSql = strSql & "CLng(Right(" & Fld.Name & ", Len(" & Fld.Name & ") - InStr(" & Fld.Name & ", '.')))" & " AS [Pos], "

when i try to replicate your code i get the following:
a) Not sure if it is the problem but you have two columns names [NoName] so you need to distinguish between the two. (b) Could you to put the NoName columns in square brackets and try single quotes instead of double quotes?
SELECT
CLng(Replace(Left(NoName, InStr(NoName, ".") - 1), "G", "")) AS [GVal],
CLng(Right(NoName, Len(NoName) - InStr(NoName, "."))) AS [Pos], [SomeAggr] AS [Aggr],
NoName,
[Div1] AS [DV A],
[Div2] AS [DV B],
[Div3] AS [DV C]
FROM
`C:\Temp`\Test.csv

Related

Error in Macro VBA. runtime error '-2147217900 (80040e14)' incorrect syntax error ')'

This is the code I have can't figure why it is giving error. Debug brings me at Conn.Execute (strSQL) this line. I tried couple of fixes from online like removing quotes from around values but it didnt help
If Not RS.EOF Then
nObjectId = RS("OBJECTID")
While x < 17
If tbProp(x, nGroup) <> "-1" Then
If Not IsError(.Cells(y, x)) Then
If Not IsNumeric(.Cells(y, x)) Or InStr(.Cells(y, x), "<") > 0 Then
strSQL = " INSERT INTO info_objectvalue(SCENARIOID ,PROPERTYID,PRODUCTID,CLIENTID,SERVICEID,OBJECTID,PROPERTYLOOKUP,PROPERTYVALUENUM)"
strSQL = strSQL & " VALUES(0 ," & tbProp(x, nGroup) & "," & nProductId & ",1,129," & nObjectId & ",0,0)"
Conn.Execute (strSQL)
Else
strSQL = " INSERT INTO info_objectvalue(SCENARIOID ,PROPERTYID,PRODUCTID,CLIENTID,SERVICEID,OBJECTID,PROPERTYLOOKUP,PROPERTYVALUENUM)"
strSQL = strSQL & " VALUES(0 ," & tbProp(x, nGroup) & "," & nProductId & ",1,129," & nObjectId & ",0," & Replace(.Cells(y, x), ",", ".") & ")"
Conn.Execute (strSQL)
End If
End If
End If
x = x + 1
Wend
End If
End If
y = y + 1
Wend
End With

SQL in VBA right join with no data from first table

I try to join data from multiple workbooks and use it in current workbook instead of VLOOKUP function. So I do not want return key column, just those that match criteria in key column in current workbook.
I got "Syntax error in FROM clause."
Everything works fine without "RIGHT JOIN" part. I use ADO.
"SELECT t1.number " & _
"FROM" & _
"(SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Src1.xlsm' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] " & _
"UNION ALL " & _
"SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Src2.xlsb' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;']" & _
"UNION ALL " & _
"SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Src2.xlsb' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;']) t1" & _
"RIGHT JOIN [Sheet1$] " & _
"IN '" & ThisWorkbook.FullName & "' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] t2 ON t2.key = t1.key;"
Data looks like
ThisWorkbook.Fullname:
key | someColumns | number
k1 | somedata |
k3 | somedata |
k5 | somedata |
\Src1.xlsm (also Src2):
key | number
k1 | 15
k2 | 11
k3 | 8
k4 | 16
k5 | 7
Likely result in Thisworkbook.fullname
key | someColumns | number
k1 | somedata | 15
k3 | somedata | 8
k5 | somedata | 7
Try
Dim Ws As Worksheet
Dim Rs As Object
Sub getRs(strSQL As String)
Dim strConn As String
Dim i As Integer
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties=Excel 12.0;"
Set Rs = CreateObject("ADODB.Recordset")
Rs.Open strSQL, strConn
End Sub
Sub test()
Dim strQuery As String
strQuery = "SELECT t1.number " & _
"FROM [Sheet1$] as t2 LEFT JOIN " & _
"(SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Src1.xlsm' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;'] " & _
"UNION ALL " & _
"SELECT * FROM [Sheet1$] " & _
"IN '" & ThisWorkbook.Path & "\Src2.xlsb' " & _
"[Excel 12.0;Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Extended Properties='HDR=YES;']) as t1 " & _
"ON t1.key = t2.key Where not isnull(t2.key) "
getRs strQuery
Range("c2").CopyFromRecordset Rs
Rs.Close
Set Rs = Nothing
End Sub

Quotations in Access String from Excel VBA

Ok I am having a Problem using VBA from Excel 2010 to Query data in access, the problem comes when the variable Descripcheck, or Grouplocal, some of the descriptions have a "" in the excel cell so when it pulls the string itself this causes the query function gets a syntax error. Any ideas?
PMnum = Cells(B, 3)
Grouplocal = Cells(B, 4)
Descripcheck = Cells(B, 6)
DevTyp = Cells(B, 5)
TagName = Cells(B, 2)
If PMnum = "" Then
PMnum = " IS NULL"
Else:
PMnum = "=" & PMnum
End If
If Grouplocal = "" Then
Grouplocal = " IS NULL"
Else:
Grouplocal = "=" & Chr$(34) & Grouplocal & Chr$(34)
End If
If Descripcheck = "" Then
Descripcheck = " IS NULL"
Else:
Descripcheck = "=" & Chr$(34) & Descripcheck & Chr$(34)
End If
If DevTyp = "" Then
DevTyp = " IS NULL"
Else:
DevTyp = "=" & Chr$(34) & DevTyp & Chr$(34)
End If
If TagName = "" Then
TagName = " IS NULL"
Else:
TagName = "=" & Chr$(34) & TagName & Chr$(34)
End If
sCmndString = "SELECT Site_Data.Pass_Fail, Site_Data.Tag_Name, Site_Data.[PM_#],Site_Data.Group_Location_Reference, Site_Data.Device_Type, Site_Data.Description, Site_Data.Set_Point, Site_Data.Set_Point_Units, Site_Data.Fail_Low, Site_Data.Fail_High, Site_Data.As_Found, Site_Data.As_Left, Site_Data.Manufacturer_SN, Site_Data.Year_Put_Into_Service, Site_Data.Date_of_Test, Site_Data.Time_To_Complete, Site_Data.Service, Site_Data.Comments, Site_Data.Site, Site_Data.Year, Site_Data.Month " & _
"FROM Site_Data WHERE (((Site_Data.[PM_#])" & PMnum & ") AND " & _
"((Site_Data.Group_Location_Reference)" & Grouplocal & ") AND " & _
"((Site_Data.Device_Type)" & DevTyp & ") AND " & _
"((Site_Data.Description)" & Descripcheck & ") AND " & _
"((Site_Data.Site)=" & Chr$(34) & SiteName & Chr$(34) & ") AND " & _
"((Site_Data.Year)=" & Chr$(34) & yrs & Chr$(34) & ") AND " & _
"((Site_Data.Month)=" & Chr$(34) & Mnth & Chr$(34) & ") AND " & _
"((Site_Data.Tag_Name)" & TagName & "));"
Set rs = New ADODB.Recordset
rs.Open sCmndString, cnt, 2, 3, 1
If you keep fooling around with those "s and Chr$(34)s you'll drive yourself crazy. Try using a parameterized query instead. Consider the following (simplified) example. It uses some test data in Access...
Site_ID Device_Type Description
------- ----------- ------------
1 Type1 test1
2 Type1
3 Type1
4 Type2 "some" value
5 Type2 "some" value
6 Type2
7 Type2
8 Type2
...an Excel sheet that looks like this...
...and the code behind the button is
Option Explicit
Public Sub AccessLookup()
Dim con As ADODB.Connection, cmd As ADODB.Command, rst As ADODB.Recordset
Dim DevTyp As Variant, Descripcheck As Variant
Dim s As String, i As Long
s = Trim(CStr(Range("B1").Value))
DevTyp = IIf(Len(s) = 0, Null, s)
s = Trim(CStr(Range("B2").Value))
Descripcheck = IIf(Len(s) = 0, Null, s)
Set con = New ADODB.Connection
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Public\Database1.accdb;"
Set cmd = New ADODB.Command
cmd.ActiveConnection = con
cmd.CommandText = _
"SELECT COUNT(*) AS n FROM Site_Data " & _
"WHERE Device_Type " & IIf(IsNull(DevTyp), "IS NULL ", "= ? ") & _
"AND Description " & IIf(IsNull(Descripcheck), "IS NULL ", "= ? ")
i = 0
If Not IsNull(DevTyp) Then
cmd.CreateParameter "?", adVarWChar, adParamInput, 255
cmd.Parameters(i).Value = DevTyp
i = i + 1
End If
If Not IsNull(Descripcheck) Then
cmd.CreateParameter "?", adVarWChar, adParamInput, 255
cmd.Parameters(i).Value = Descripcheck
i = i + 1
End If
Set rst = cmd.Execute
Range("B6").Value = rst("n").Value
rst.Close
Set rst = Nothing
Set cmd = Nothing
con.Close
Set con = Nothing
End Sub

How to merge two database tables when only some fields are common?

In MS Access I have two tables (A and B), and the task is to insert B into A. However, there are some special conditions:
All fields are of type text.
A and B have a some common fields.
The same key field is guaranteed to exist in both, and its values to be always different.
A has some fields that B does not have. The inserted records should have those fields blank.
B has some fields that A does not have. These fields must be created in A, and the existing records in A should have them blank.
There are many cases like this one, so the query should not explicitly include the field names, since it would be tedious to personalize the query for each case. However, the key field is always named the same.
Creating a new table C instead of directly replacing A is acceptable.
Example:
Table A:
key a b c
--- ------- ------- -------
k0 hello dear world
k1 bye cruel world
Table B:
key a d e
--- ------- ------- -------
k2 welcome john doe
k3 turulu ann harp
Table C (the new A):
key a b c d e
--- ------- ------- ------- ------- -------
k0 hello dear world
k1 bye cruel world
k2 welcome john doe
k3 turulu ann harp
Create an Access Module and use the following code. Replace the values in the test sub with your table and destination names
Option Compare Database
Option Explicit
Function SplatTablesSql(pT1 As String, pT2 As String, pDest As String)
Dim lDb As Database
Dim lTd1 As TableDef, lTd2 As TableDef
Dim lField As Field, lF2 As Field
Dim lS1 As String, lS2 As String, lSep As String
SplatTablesSql = "Select "
lS1 = "Select "
lS2 = "Select "
Set lDb = CurrentDb
Set lTd1 = lDb.TableDefs(pT1)
Set lTd2 = lDb.TableDefs(pT2)
For Each lField In lTd1.Fields
SplatTablesSql = SplatTablesSql & lSep & "x.[" & lField.Name & "]"
lS1 = lS1 & lSep & "a.[" & lField.Name & "]"
Set lF2 = Nothing
On Error Resume Next
Set lF2 = lTd2.Fields(lField.Name)
On Error GoTo 0
If lF2 Is Nothing Then
lS2 = lS2 & lSep & "Null"
Else
lS2 = lS2 & lSep & "b.[" & lField.Name & "]"
End If
lSep = ", "
Next
For Each lField In lTd2.Fields
Set lF2 = Nothing
On Error Resume Next
Set lF2 = lTd1.Fields(lField.Name)
On Error GoTo 0
If lF2 Is Nothing Then
SplatTablesSql = SplatTablesSql & lSep & "x.[" & lField.Name & "]"
lS1 = lS1 & lSep & "Null as [" & lField.Name & "]"
lS2 = lS2 & lSep & "b.[" & lField.Name & "]"
End If
lSep = ", "
Next
SplatTablesSql = SplatTablesSql & " Into [" & pDest & "] From ( " & lS1 & " From [" & pT1 & "] a Union All " & lS2 & " From [" & pT2 & "] b ) x"
End Function
Sub Test()
CurrentDb.Execute SplatTablesSql("a", "b", "c")
End Sub
The easiest way I can think to solve this is to use VBA to create the query definition.
I will assume that there's a column named key which is common to both tables.
I found here that you can use collections to make a dictionary-like structure. I'll use that to build the field list.
So, here we go:
public function contains(col as Collection, key as variant) as boolean
dim obj as variant
on error goto err
contains = True
obj = col(key)
exit function
err:
contains = false
end function
public sub create_this_query(tbl1 as String, tbl2 as String, keyField as String)
' tbl1 and tbl2 are the names of the tables you'll use
dim db as DAO.database, rs1 as DAO.recordset, rs2 as DAO.recordset
dim columns as Collection
dim strSQL as String
dim i as integer
dim obj as variant, colName as String
set db = currentdb()
set tbl1 = db.openrecordset(tbl1, dbopendynaset, dbreadonly)
set tbl2 = db.openrecordset(tbl2, dbopendynaset, dbreadonly)
set columns = new Collection
' Let's create the field list (ommiting the keyField)
for i = 1 to tbl1.fields.count
if not contains(columns, tbl1.fields(i).Name) _
and tbl1.fields(i).Name <> keyField then
columns.add tbl1.fields(i).Name, tbl1.fields(i).Name
end if
next i
for i = 1 to tbl2.fields.count
if not contains(columns, tbl2.fields(i).Name) _
and tbl2.fields(i).Name <> keyField then
columns.add tbl1.fields(i).Name, 1 ' The value is just a placeholder
end if
next i
' Now let's build the SQL instruction
strSQL = "select [a].[" & keyField & "]"
for colName in columns
strSQL = strSQL & ", [" & colName & "]"
next obj
strSQL = strSQL & " " & _
"from " & _
" (" & _
" select [" & keyField & "] from [" & tbl1 & "] " & _
" union " & _
" select [" & keyField & "] from [" & tbl2 & "] " & _
" ) as a " & _
"left join [" & tbl1 & "] as t1 " & _
" on a.[" & keyField & "] = t1.[" & keyField & "] " & _
"left join [" & tbl2 & "] as t2 " & _
" on a.[" & keyField & "] = t2.[" & keyField & "] "
' Finally, let's create the query object
db.createQueryDef("myNewQuery", strSQL)
end sub
Hope this helps

Left Join works with table but fails with query

The following left join query in MS Access 2007
SELECT
Table1.Field_A,
Table1.Field_B,
qry_Table2_Combined.Field_A,
qry_Table2_Combined.Field_B,
qry_Table2_Combined.Combined_Field
FROM Table1
LEFT JOIN qry_Table2_Combined
ON (Table1.Field_A = qry_Table2_Combined.Field_A)
AND (Table1.Field_B = qry_Table2_Combined.Field_B);
is expected by me to return this result:
+--------+---------+---------+---------+----------------+
|Field_A | Field_B | Field_A | Field_B | Combined_Field |
+--------+---------+---------+---------+----------------+
|1 | | | | |
+--------+---------+---------+---------+----------------+
|1 | | | | |
+--------+---------+---------+---------+----------------+
|2 |1 |2 |1 |John, Doe |
+--------+---------+---------+---------+----------------+
|2 |2 | | | |
+--------+---------+---------+---------+----------------+
[Table1] has 4 records, [qry_Table2_Combined] has 1 record.
But it gives me this:
+--------+---------+---------+---------+----------------+
|Field_A | Field_B | Field_A | Field_B | Combined_Field |
+--------+---------+---------+---------+----------------+
|2 |1 |2 |1 |John, Doe |
+--------+---------+---------+---------+----------------+
|2 |2 |2 | |, |
+--------+---------+---------+---------+----------------+
Really weird is that the [Combined_Field] has a comma in the second row. I use a comma to concatenate two fields in [qry_Table2_Combined].
If the left join query uses a table created from the query [qry_Table2_Combined] it works as expected.
Why does this left join query not give the same result for a query and a table? And how can i get the right results using a query in the left join?
Looking at you logic, it seems that you only want combined fields where field_A = "2" (SELECT '2' AS Field_A). I suspect that this is causing the problem. Would it be possible to go about a solution in a different way, for example:
SELECT
t1.Field_A,
t1.Field_B,
t2.Field_B As t2B,
[t2].[Col_1] & ", " & [t2].[Col_2] AS Combined
FROM t1 LEFT JOIN t2
ON t1.Field_B = t2.Field_B
WHERE t1.Field_A="2"
UNION ALL
SELECT
t1.Field_A,
t1.Field_B,
"None" As t2B,
"None" AS Combined
FROM t1
WHERE t1.Field_A<>"2"
Concatenation: change the & operators to + operators and the result should be as expected.
Missing rows: I can reproduce this issue but cannot explain it, other than to say a) it's probably a bug and b) it will probably never get fixed :(
For sanity I tested the same code in SQL Server and it works as expected.
As a general point an outer join can be simulated using union and padding the missing values e.g. pseudo code:
( A JOIN B )
UNION
( A NOT MATCH B { A.*, <pad values for B> } )
In your case and in Access SQL:
SELECT Table1.Field_A, Table1.Field_B,
qry_Table2_Combined.Field_A,
qry_Table2_Combined.Field_B,
qry_Table2_Combined.Combined_Field
FROM Table1
INNER JOIN qry_Table2_Combined
ON (Table1.Field_A = qry_Table2_Combined.Field_A)
AND (Table1.Field_B = qry_Table2_Combined.Field_B)
UNION ALL
SELECT Table1.Field_A, Table1.Field_B,
NULL AS Field_A,
NULL AS Field_B,
NULL AS Combined_Field
FROM Table1
WHERE NOT EXISTS ( SELECT *
FROM qry_Table2_Combined
WHERE (Table1.Field_A = qry_Table2_Combined.Field_A)
AND (Table1.Field_B = qry_Table2_Combined.Field_B) );
The above seems to produce the results you were expecting.
Access repro code, with concatenation fix, uncomment code for suggested workaround:
Sub EXfewfTempler()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
With .ActiveConnection
Dim Sql As String
Sql = "CREATE TABLE Table1 ( Field_A VARCHAR(10), Field_B VARCHAR(10) );"
.Execute Sql
Sql = "CREATE TABLE Table2 ( Field_B VARCHAR(10), Col_1 VARCHAR(10), Col_2 VARCHAR(10));"
.Execute Sql
Sql = "CREATE VIEW qry_Table2_Combined AS SELECT '2' AS Field_A, Table2.Field_B, Table2.Col_1 + ', ' + Table2.Col_2 AS Combined_Field FROM Table2; "
.Execute Sql
Sql = "INSERT INTO Table1 VALUES (1, NULL);"
.Execute Sql
Sql = "INSERT INTO Table1 VALUES (1, NULL);"
.Execute Sql
Sql = "INSERT INTO Table1 VALUES (2, 1);"
.Execute Sql
Sql = "INSERT INTO Table1 VALUES (2, 2);"
.Execute Sql
Sql = "INSERT INTO Table2 VALUES (1, 'John', 'Doe');"
.Execute Sql
Sql = _
"SELECT " & _
"Table1.Field_A, " & _
"Table1.Field_B, " & _
"qry_Table2_Combined.Field_A, " & _
"qry_Table2_Combined.Field_B, " & _
"qry_Table2_Combined.Combined_Field " & _
"FROM Table1 " & _
"LEFT JOIN qry_Table2_Combined " & _
" ON (Table1.Field_A = qry_Table2_Combined.Field_A) " & _
"AND (Table1.Field_B = qry_Table2_Combined.Field_B);"
' Sql = _
' "SELECT Table1.Field_A, Table1.Field_B, " & _
' " qry_Table2_Combined.Field_A, " & _
' " qry_Table2_Combined.Field_B, " & _
' " qry_Table2_Combined.Combined_Field " & _
' " FROM Table1 " & _
' " INNER JOIN qry_Table2_Combined " & _
' " ON (Table1.Field_A = qry_Table2_Combined.Field_A) " & _
' " AND (Table1.Field_B = qry_Table2_Combined.Field_B) " & _
' "UNION ALL " & _
' "SELECT Table1.Field_A, Table1.Field_B, " & _
' " NULL AS Field_A, " & _
' " NULL AS Field_B, " & _
' " NULL AS Combined_Field " & _
' " FROM Table1 " & _
' " WHERE NOT EXISTS ( SELECT * " & _
' " FROM qry_Table2_Combined " & _
' " WHERE (Table1.Field_A = qry_Table2_Combined.Field_A) " & _
' " AND (Table1.Field_B = qry_Table2_Combined.Field_B) );"
Dim rs
Set rs = .Execute(Sql)
MsgBox rs.GetString(2, , vbTab & vbTab, , "<NULL>")
End With
Set .ActiveConnection = Nothing
End With
End Sub
isn't this a problem with MSAccess parsing. for a test change the field names in the query to Field_C and Field_D and see if you still have the same problem