%% Select Data Using Variable in Query
% Import product data from a Microsoft(R) SQL Server(R) database into
% MATLAB(R) by using an ODBC connection and a variable in the SQL |SELECT|
% statement.
%
%%
% Create an ODBC database connection to a Microsoft(R) SQL Server(R)
% database with Windows(R) authentication. Specify a blank user name and
% password. The database contains the table |productTable|.

datasource = 'MS SQL Server Auth';
conn = database(datasource,'','');

%%
% Check the database connection. If the |Message| property is
% empty, then the connection is successful.

conn.Message

%%
% Select all the data from |productTable| by specifying the product
% description as a variable. Import the data from the executed query using
% the |fetch| function.
%
% The SQL |SELECT| statement uses square brackets to concatenate the two
% character vectors. To create the pair of single quotation marks that
% appears in the SQL |SELECT| statement, specify two sets of four single
% quotation marks around |productdesc|. The outer two marks delineate the
% next character vector for concatenation. The two inner marks denote a
% quotation mark inside a character vector.

productdesc = 'Painting Set';
sqlquery = ['SELECT * FROM productTable ' ...
    'WHERE productDescription = ' '''' productdesc '''']; 
results = fetch(conn,sqlquery)

%%
% Instead of a variable, use the character vector |'Slinky'| to import
% data.

sqlquery = ['SELECT * FROM productTable ' ... 
    'WHERE productDescription = ' '''Slinky'''];
results = fetch(conn,sqlquery)

%%
% Close the database connection.

close(conn)