%% Customize Options When Importing Categorical Array Data
% Customize import options when importing categorical array data from a database table. Control the import options by creating an SQLImportOptions object. Then, customize the import options for database columns that contain categorical array data. Import data using the sqlread function.
% This example uses the outages.csv file, which contains the columns Region and Cause. 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 outage information into the MATLAB® workspace.

outages = readtable('outages.csv');

% Create the outages database table using the outage information.

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

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

opts = databaseImportOptions(conn,tablename);

%
% Retrieve the default import options for the Region and Cause variables.

varnames = {'Region','Cause'};
varOpts = getoptions(opts,varnames)

%
% Set the import options for the data type of the specified variables to categorical. Also, set the import options to replace missing data in the specified variables with the fill value unknown.

opts = setoptions(opts,varnames,'Type','categorical', ...
    'FillValue','unknown');

%
% Import the categorical array data in the selected variables and display a summary of the data. The imported data shows that the variables have the categorical data type. The missing values of both variables are filled with the value unknown.

opts.SelectedVariableNames = varnames;
T = sqlread(conn,tablename,opts);
summary(T)

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

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

% Close the database connection.

close(conn)