%% Customize Options When Importing Numeric Data
% Customize import options when importing numeric data from a database table. Control the import options by creating an SQLImportOptions object. Then, customize the import options for a numeric database column. Import data using the sqlread function.
% This example uses the patients.xls spreadsheet, which contains the column Weight. Also, the example uses a Microsoft® SQL Server® Version 11.00.2100 database and the Microsoft SQL Server Driver 11.00.5058.
%
% Create a 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)

%
% Create an SQLImportOptions object using the patients database table and the databaseImportOptions function.

opts = databaseImportOptions(conn,tablename);

%
% Customize the import options for the Weight column in the patients database table. Because this column is numeric, change the data type to int64.

varnames = 'Weight';
opts = setoptions(opts,varnames,'Type','int64');

%
% Import the numeric data in the specified column and display a summary of the imported variable. The summary shows that the variable has the int64 data type.

opts.SelectedVariableNames = {'Weight'};
data = sqlread(conn,tablename,opts);
summary(data)

%
% 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.