Using XML to pass lists as parameters in SQL Server: the C# Side

The blog post “Using XML to pass lists as parameters in SQL Server” by the wonderfully-named Phil Factor outlines a useful technique to pass lists into stored procedures and functions. Here is a simple function to create the appropriate XML in C# code (assumes it is a list of integers):

/// <summary>
/// Formats a list of integers for use as a parameter to a sql function.
/// </summary>
/// <remarks>
/// SQL:
/// <code>SELECT x.y.value('.','int') AS IDs FROM @XMLList.nodes('/list/i/text()') AS x(y)</code>
/// Courtesy of https://www.simple-talk.com/blogs/using-xml-to-pass-lists-as-parameters-in-sql-server/.
/// </remarks>
public static XElement ListIntegersAsXElementsForSqlParameter(IEnumerable<int> values)
{
	if (!values.Any())
	{
		return null;
	}

	XElement node = new XElement("list");
	foreach (int value in values)
	{
		node.Add(new XElement("i", value));
	}

	return node;
}