%% Create DatabaseDatastore Object Using Custom Import Options
% Customize import options when importing a large data set from a database table. Control the import options by creating an SQLImportOptions object. Then, customize the import options for database columns that contain logical data. Import and preview the data by creating a DatabaseDatastore object and using the preview function.
% This example uses the airlinesmall_subset.xls spreadsheet, which contains the column Cancelled. 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 flight information into the MATLAB® workspace.

flights = readtable('airlinesmall_subset.xlsx');

% Create the flights database table using the flight information.

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

%
% Create an SQLImportOptions object using the flights database table with the databaseImportOptions function.

opts = databaseImportOptions(conn,tablename);

%
% Retrieve the default import options for the Cancelled variable.

varnames = 'Cancelled';
varOpts = getoptions(opts,varnames)

%
% Set the import options for the data type of the specified variable to logical. Also, set the import options to replace missing data in the specified variable with the fill value true.

opts = setoptions(opts,varnames,'Type','logical', ...
    'FillValue',true);

%
% Create the DatabaseDatastore object to import a large data set using the import options.

dbds = databaseDatastore(conn,tablename,opts);

%
% Import the logical data in the selected variable and display a preview of the data. The imported data shows that the variable has the logical data type.

opts.SelectedVariableNames = varnames;
data = preview(dbds);
cancelled = data.Cancelled

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

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

% Close the database connection.

close(conn)

% Copyright 2018 The MathWorks, Inc.