Main Content

Generate SQL Query andMATLABScript

You can generate SQL code from an SQL query or create a MATLAB®script by using theDatabase Explorerapp. After defining an SQL query in theSQL Querypane, you can generate the SQL code for running an SQL script. You can also generate a MATLAB script to automate connecting to a database, running an SQL query, and performing data analysis on the imported data.

Generate SQL Query

To generate SQL code from an SQL query, follow these steps:

  1. Connect to a data source and create an SQL query. For details about creating SQL queries, seeCreate SQL Queries Using Database Explorer App.

  2. In theImportsection, selectImport Data>Generate SQL Query.

  3. Save the SQL code to a.txtor.sqlfile. The MATLAB Editor opens the saved SQL code file.

    The Editor tab shows the testquery.sql file that contains the SQL SELECT query that selects the productnumber, stocknumber, suppliernumber, and unitcost columns from the producttable database table.

    You can use the SQL code to rebuild a query by using theSQL Querypane by entering the SQL code manually.

    Alternatively, you can use the.sqlfile to import data programmatically into MATLAB by using theexecuteSQLScriptfunction.

GenerateMATLABScript

To generate a MATLAB script that automates connecting to a data source, running an SQL query, and importing the SQL query results, follow these steps:

  1. Connect to a data source and create an SQL query. For details about creating SQL queries, seeCreate SQL Queries Using Database Explorer App.

  2. In theImportsection, selectImport Data>Generate MATLAB Scriptto display a MATLAB script in the MATLAB Editor. To customize import options before importing data, seeCustomize Import Options Using Database Explorer App.

    The Editor tab shows an Untitled file that contains the generated code that connects to the Microsoft SQL Server database by using an authenticated connection. The code also writes the SQL SELECT query that selects the productNumber, Quantity, and Price columns from the inventoryTable database table, executes and returns the results of the SQL query, and closes the database connection.

  3. Save the MATLAB script. You can run this script at the command line.

    Note

    To run the script, enter the database password as an input argument of thedatabasefunction in the script.

For details about editing and running scripts, seeScripts.

See Also

Functions

Apps

Related Topics