%% Import Data from SQL Query as Structure
% Specify the data return format and the number of imported rows for the results of an SQL query. Import data using an SQL query and the fetch function.
% This example uses a Microsoft® SQL Server® Version 11.00.2100 database and the Microsoft SQL Server Driver 11.00.5058.
%
% Create an ODBC database connection to a Microsoft SQL Server database with Windows® authentication. Specify a blank user name and password.

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

%
% Load patient information into the MATLAB® workspace.

patients = readtable('patients.xls');

%
% Create the patients database table using the patient information.

tablename = 'patients';
sqlwrite(conn,tablename,patients)

%
% Select all data from the patients database table and import five rows from the table as a structure. Use the 'DataReturnFormat' name-value pair argument to specify returning the result data as a structure. Also, use the 'MaxRows' name-value pair argument to specify five rows. Display the imported data.

sqlquery = ['SELECT * FROM ' tablename];
results = fetch(conn,sqlquery,'DataReturnFormat','structure', ...
    'MaxRows',5)

%
% Delete the patients database table using the execute function.

sqlquery = ['DROP TABLE ' tablename];
execute(conn,sqlquery)

%
% Close the database connection.

close(conn)

% Copyright 2018 The MathWorks, Inc.