Customize import options when importing text data from a database table. Control the import options by creating an SQLImportOptions object. Customize the import options for a text database column. Preview the database data before importing data. Then, import the data using the sqlread function.
This example uses the patients.xls spreadsheet, which contains the first column LastName. 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.
Load patient information into the MATLAB® workspace.
Create the patients database table using the patient information.
Create an SQLImportOptions object using the patients database table and the databaseImportOptions function.
Retrieve the default import options for the LastName variable.
varOpts =
SQLVariableImportOptions with properties:
Variable Properties :
Name: 'LastName'
Type: 'char'
MissingRule: 'fill'
FillValue: ''
String Properties :
WhitespaceRule: 'preserve'
TextCaseRule: 'preserve'
Set the import options for the data type of the LastName variable to string. Specify the LastName variable by using a numeric index that finds the variable within the SelectedVariables property of the SQLImportOptions object. Also, set the import options to replace missing data in the LastName variable with the NoName fill value.
Preview the first eight rows of database data using the import options. The data preview shows that the LastName variable has the string data type.
T=8×10 table
LastName Gender Age Location Height Weight Smoker Systolic Diastolic SelfAssessedHealthStatus
__________ ________ ___ ___________________________ ______ ______ ______ ________ _________ ________________________
"Smith" 'Male' 38 'County General Hospital' 71 176 1 124 93 'Excellent'
"Johnson" 'Male' 43 'VA Hospital' 69 163 0 109 77 'Fair'
"Williams" 'Female' 38 'St. Mary's Medical Center' 64 131 0 125 83 'Good'
"Jones" 'Female' 40 'VA Hospital' 67 133 0 117 75 'Fair'
"Brown" 'Female' 49 'County General Hospital' 64 119 0 122 80 'Good'
"Davis" 'Female' 46 'St. Mary's Medical Center' 68 142 0 121 70 'Good'
"Miller" 'Female' 33 'VA Hospital' 64 142 1 130 88 'Good'
"Wilson" 'Male' 40 'VA Hospital' 68 180 0 115 82 'Good'
Import the text data in the selected variable and display the first eight rows. The imported data shows that the variable has the string data type.
ans=8×1 table
LastName
__________
"Smith"
"Johnson"
"Williams"
"Jones"
"Brown"
"Davis"
"Miller"
"Wilson"
Delete the patients database table using the execute function.
Close the database connection.