This question was from 2012 for SQL Server 2008, and I wonder if with SQL Server 2016 and up it still is relevant: Should you make multiple insert calls or pass XML?
The argument in the above post is that the preparedocument
and OPENXML
are expensive calls and confusing to work with.
This post Save Array Or List Of Records As XML Data To SQL Server in one call seems to disagree with the previous post, but also mentions nothing about performance.
I have an entity that has a child properties of EntityTranslations
which is a List<Translations>
.
My issue with using a table type is that I find it to be clumsy on the .net side of the application.
Setting up the dataTable, columns, looping to insert each record into the table, then having a hard-coded reference to the new database table type something like
DataTable translationDataTable = new DataTable("Translation");
translationDataTable.Columns.Add("Name", typeof(string));
translationDataTable.Columns.Add("Description", typeof(string));
translationDataTable.Columns.Add("Language", typeof(string));
foreach (Translation t in entityTranslations)
{
DataRow newRow = translationDataTable.NewRow();
newRow["Name"] = entityTranslations.Name;
newRow["Description"] = entityTranslations.Description;
newRow["Language"] = entityTranslations.Language;
translationDataTable.Rows.Add(newRow);
}
List<IDbDataParameter> parameters = new List<IDbDataParameter>
{
new SqlParameter("@Translations", SqlDbType.Structured)
{
TypeName = "dbo.TranslationTableType",
Value = translationDataTable
},
new SqlParameter("CountryCode", countryCode),
};
It's the TypeName = "dbo.TranslationTableType",
I take issue with
VS
XmlSerializer xml = new XmlSerializer(typeof (List<Translation>));
using (MemoryStream memoryStream = new MemoryStream())
{
xml.Serialize(memoryStream, entityTranslations);
List<IDbDataParameter> parameters = new List<IDbDataParameter>();
parameters.Add(new SqlParameter("Translations", Encoding.UTF8.GetString(memoryStream.ToArray())));
parameters.Add(new SqlParameter("CountryCode", countryCode));
}
The question: is there a performance hit with SQL Server 2016 when inserting multiple rows via XML vs structure table vs many small inserts (and being part of a transaction on the .net side of code)?