How can I retrieve the output if I execute an INSERT query with an OUTPUT clause with the Database Toolbox?

6 visualizzazioni (ultimi 30 giorni)
I am working with Microsoft SQL Server (which uses the Transact-SQL dialect of SQL) and I am executing an INSERT statement like the following:
% conn = database(...)\nsqlquery = 'INSERT INTO myTable (price) OUTPUT (INSERTED.ID) VALUES (3.14)';\ncursor = exec(conn, sqlquery)
But whenever I go to get the returned information (from the OUTPUT clause), I see the following:
 
>> cursor.Data\nans =\n 0\n\n>> cursor.Message\nans =\n 'Invalid Cursor: A result set was generated for update.'
How can I get the data that is returned? Even though this isn't a SELECT query, I should be getting data back.

Risposta accettata

MathWorks Support Team
MathWorks Support Team il 1 Feb 2022
You should use the 'fetch' command directly with your SQL query, rather than using the 'exec' function. For example:
% conn = database(...)\nsqlquery = 'INSERT INTO myTable (price) OUTPUT (INSERTED.ID) VALUES (3.14)';\nresults = fetch(conn, sqlquery)
After running this code, the "results" variable should contain the information that you expect. Note that the format of "results" depends on the 'DataReturnFormat'. For more information, see the documentation for the 'fetch' function:

Più risposte (0)

Prodotti


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by