User`s guide

6 Using Database Toolbox Functions
6-12
Create a Query Using a MATLAB Variable
This example shows how to include a MATLAB variable in your SQL query. This
example uses a Microsoft SQL Server database.
Connect to the Database
Connect to the Microsoft SQL Server database using a JDBC driver without operating
system authentication. For example, this code assumes you are connecting to a database
named dbname with the user name username, password pwd, database server name
sname, and port number 123456.
conn = database('dbname','username','pwd',...
'Vendor','Microsoft SQL Server','Server','sname',...
'AuthType','Server','portnumber',123456);
Create a Query Using a MATLAB Variable
Suppose you want to select all invoice data for the first product. Create a MATLAB
variable productID and set it to the first product number.
productId = 1;
Select all records from the table invoice where the product number is equal to the first
product. Create an SQL query string sqlquery that concatenates the SQL query with
the MATLAB variable productID by using brackets. productID is a numeric variable
but the SQL query is a string. You need convert the number to a string by using the
num2str function.
sqlquery = ['select * from invoice '...
'where ProductNumber = ' num2str(productId)];
Execute the Query
Execute the SQL query using the exec function and display the data using the fetch
function.
curs = exec(conn,sqlquery);
curs = fetch(curs);
curs.Data
ans =