Is it possible to use an array or dictionary as the table in a SQL statement.
e.g. strSQL = \"SELECT * FROM \" & myArray & \"\"
Thanks in advance.
SQL array like search function:
SELECT TABLEARRAY.*
FROM (
SELECT P.*
FROM Person P
WHERE P.id IN (1, 2, 3, 4, 18) --This would be your array with ID's
) AS TABLEARRAY
Dim a(3) As Variant
a(0) = 1
a(1) = 2
a(2) = 3
a(3) = 4
Debug.Print "select * from xyz where id in (" & Join(a, ",") & ")"
Expanding upon the idea provided by @Nathan_Sav the following code should to it:
Dim a(3) As String
a(0) = "1 as C1"
a(1) = 2
a(2) = 3
a(3) = 4
Debug.Print "select * from (SELECT " & Join(a, " UNION ALL SELECT ") & ") as tmp"
Here is a short sub to manually concatenate / construct the necessary string:
Option Explicit
Sub tmpTest()
Dim strSQL As String
Dim varArray As Variant
Dim lngRow As Long, lngColumn As Long
varArray = ThisWorkbook.Worksheets(1).Range("A1:G12")
strSQL = "select * from "
strSQL = strSQL & "(select "
For lngRow = LBound(varArray, 1) + 1 To UBound(varArray, 1)
For lngColumn = LBound(varArray, 2) To UBound(varArray, 2)
'First row must contain column names
If lngRow = LBound(varArray, 1) + 1 Then
strSQL = strSQL & varArray(lngRow, lngColumn) & _
" as [" & varArray(lngRow - 1, lngColumn) & "], "
Else
strSQL = strSQL & varArray(lngRow, lngColumn) & ", "
End If
'Beyond the last column a UNION ALL SELECT must be added
' except for the last row
If lngColumn = UBound(varArray, 2) And _
lngRow < UBound(varArray, 1) Then
strSQL = Mid(strSQL, 1, Len(strSQL) - 2) & _
" union all select "
End If
Next lngColumn
Next lngRow
strSQL = Mid(strSQL, 1, Len(strSQL) - 2) & ") as tmp"
Debug.Print strSQL
End Sub
The above code assumes the data to be on sheet1 in the range A1:G12
where the first row contains the columns headers.