Dit QuoteName
funktionen skal kontrollere længden, fordi funktionen T-SQL QUOTENAME angiver den maksimale længde, den returnerer. Brug dit eksempel:
String.Format(@"declare @delimitedIdentifier nvarchar(258);
set @delimitedIdentifier = {0};", QuoteName(identifier));
Hvis QuoteName(identifier)
er længere end 258 tegn, afkortes det lydløst, når det tildeles til @delimitedIdentifier
. Når det sker, åbner du muligheden for @delimitedIdentifier
at blive undslippet forkert.
Der er an MSDN-artikel af Bala Neerumalla, en "sikkerhedssoftwareudvikler hos Microsoft", der forklarer emnet mere dybdegående. Artiklen indeholder også det nærmeste, jeg har fundet på "definitiv dokumentation om, hvordan man undslipper citerede identifikatorer i SQL Server":
Dette er den C#-kode, jeg bruger i øjeblikket:
/// <summary>
/// Returns a string with the delimiters added to make the input string
/// a valid SQL Server delimited identifier. Brackets are used as the
/// delimiter. Unlike the T-SQL version, an ArgumentException is thrown
/// instead of returning a null for invalid arguments.
/// </summary>
/// <param name="name">sysname, limited to 128 characters.</param>
/// <returns>An escaped identifier, no longer than 258 characters.</returns>
public static string QuoteName(string name) { return QuoteName(name, '['); }
/// <summary>
/// Returns a string with the delimiters added to make the input string
/// a valid SQL Server delimited identifier. Unlike the T-SQL version,
/// an ArgumentException is thrown instead of returning a null for
/// invalid arguments.
/// </summary>
/// <param name="name">sysname, limited to 128 characters.</param>
/// <param name="quoteCharacter">Can be a single quotation mark ( ' ), a
/// left or right bracket ( [] ), or a double quotation mark ( " ).</param>
/// <returns>An escaped identifier, no longer than 258 characters.</returns>
public static string QuoteName(string name, char quoteCharacter) {
name = name ?? String.Empty;
const int sysnameLength = 128;
if (name.Length > sysnameLength) {
throw new ArgumentException(String.Format(
"name is longer than {0} characters", sysnameLength));
}
switch (quoteCharacter) {
case '\'':
return String.Format("'{0}'", name.Replace("'", "''"));
case '"':
return String.Format("\"{0}\"", name.Replace("\"", "\"\""));
case '[':
case ']':
return String.Format("[{0}]", name.Replace("]", "]]"));
default:
throw new ArgumentException(
"quoteCharacter must be one of: ', \", [, or ]");
}
}