I have the following stored procedure in MySQL that reads a JSON array of objects and insert the objects in a JSON column of a temp table:
DELIMITER $$
DROP PROCEDURE IF EXISTS proc_json $$
CREATE OR REPLACE PROCEDURE myProcedure(IN myjson TEXT)
BEGIN
DECLARE i INT DEFAULT 0;
DECLARE qryStmt TEXT;
DROP TEMPORARY TABLE IF EXISTS tempTable;
CREATE TEMPORARY TABLE tempTable(update_key int NOT NULL AUTO_INCREMENT, update_data JSON, PRIMARY KEY(update_key));
WHILE i < JSON_LENGTH(myjson) DO
SET qryStmt = CONCAT("INSERT INTO tempTable VALUES(DEFAULT, (JSON_EXTRACT('", myjson,"','$[",i,"]')))");
PREPARE stmt FROM qryStmt;
EXECUTE stmt;
SET i = i+1;
END WHILE;
END $$
DELIMITER ;
The Stored Procedure works fine when I call the procedure in MySQL >CALL myProcedure('[{"firstname": "Tom", "lastname": "Cruise", "occupation": "Actor"}, {"firstname": "Al", "lastname": "Pacino", "occupation": "Actor"}]');
, it reads the string as separate JSON objects and inserts them as records in the table.
I also have the following Sub in Excel VBA that intends to call the stored procedure, passing a JSON-formatted array of objects to the stored procedure:
Sub proc_jason()
On Error GoTo ErrorHandler
Dim strConnection, jsonString As String
Set objConnection = New ADODB.Connection
Set objRecordset = New ADODB.Recordset
jsonString = "[{""firstname"": ""Tom"", ""lastname"": ""Cruise"", ""occupation"": ""Actor""}, " _
& "{""firstname"": ""Alfredo"", ""lastname"": ""Pacino"", ""occupation"": ""Actor""}]"
strConnection = "Driver={MySQL ODBC 8.0 ANSI Driver}; Server=[IP]; Database=[Db]; user=[usr]; PWD=[pwd]"
objConnection.Open strConnection
With objRecordset
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.Open "CALL myProcedure('" & jsonString & "');", objConnection, adOpenForwardOnly, adLockReadOnly, adCmdStoredProc
End With
objRecordset.Close
Set objRecordset = Nothing
objConnection.Close
Set objConnection = Nothing
Exit Sub
ErrorHandler:
MsgBox Err.Description
End Sub
The Sub returns the following error:
I’ve seen posts calling a MySQL stored procedure using the Command
object:
With objCommand
.ActiveConnection = objConnection
.CommandType = adCmdStoredProc
.CommandText = "CALL myProcedure('" & jsonString & "');"
.Execute
End With
But I still get the same error message. Any help is appreciated.
2
Answers
Thanks to Sam and CPD1802 inputs the final Sub that worked is the following:
No error message but still the Stored Procedure did not insert the records in the table. I dropped TEMPORARY in the lines of the Stored Procedure:
And now it works, for some reason using TEMPORARY TABLE when calling a Stored Procedure from Excel VBA doesn't work.
Set the parameter length to the json string length.