Newbie with SQL. I am trying to execute SQL code through a query string via excel VBA to test a dynamic pivot query from a table stored in a sheet on the same workbook. Normal query's are working perfectly (SELECT), but SQL statements not.
I receive Invalid SQL statement expected; 'DELETE','INSERT'
... error again and again
What i want to achieve is an sql query to retrieve a dynamic pivot (rows to variable columns). I don't want to achieve this with pivot tables i would like to do it with SQL string query from VBA.
How can this be done?
On Error GoTo ErrorConexion
objAdoConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & ThisWorkbook.path & "\" & ThisWorkbook.Name & ";" & _
"Extended Properties=""Excel 8.0;HDR=YES;FMT=Delimited; IMEX=1;"""
strSQL = "SET NOCOUNT ON " & Chr(13) _
& "CREATE TABLE #tempdata(tmpf1 date, tmpf2 int)" _
& " INSERT INTO #tempdata(tmpf1,tmpf2)" _
& " SELECT [DATE], [AMOUNT] FROM " & GetTableRange(StrTable)
On Error GoTo ErrorSQL
objAdoRS.Open strSQL, objAdoConn
I would like to execute code like this:
DECLARE @Category AS VARCHAR(MAX)
SELECT @Category =
COALESCE(@Category + ', ', '') + CAST(Category AS VARCHAR(20))
FROM (SELECT DISTINCT Category FROM mytable) Books
DECLARE @DynamicPIVOT AS VARCHAR(MAX)
SELECT @DynamicPIVOT = 'SELECT ' + @Category +
' FROM (
SELECT amount, Category FROM mytable
) Books
PIVOT (
MAX(amount) FOR Category IN (' + @Category + ')
) Result;'
EXEC (@DynamicPIVOT)
Regards, Vince.