private static int GetParameterPosition(string commandText, int position, char[] matchParameterIdentifiers)
{
if (commandText == null)
{
throw new ArgumentNullException("commandText");
}
if (position > commandText.Length)
{
throw new ArgumentOutOfRangeException("position");
}
var parameterPosition = commandText.IndexOfAny(matchParameterIdentifiers, position);
while (parameterPosition > -1)
{
// Ignore identifiers followed by whitespace or linebreak.
if (parameterPosition < commandText.Length && char.IsControl(commandText[parameterPosition + 1]))
{
parameterPosition = commandText.IndexOfAny(matchParameterIdentifiers, parameterPosition + 1);
continue;
}
// Ignore @@ as we would have for SELECT @@Identity.
if ((parameterPosition < commandText.Length && matchParameterIdentifiers.Contains(commandText[parameterPosition + 1]))
|| (parameterPosition > 0 && matchParameterIdentifiers.Contains(commandText[parameterPosition - 1])))
{
parameterPosition = commandText.IndexOfAny(matchParameterIdentifiers, parameterPosition + 1);
continue;
}
// Ignore identifiers inside a quoted string.
if (commandText.IndexOfAny(quoteCharacters, position, parameterPosition - position) > -1
&& commandText.IndexOfAny(quoteCharacters, parameterPosition) > -1)
{
int quoteCount = 0;
for (int i = parameterPosition; i >= 0; i--)
{
if (commandText[i] == '\'')
{
quoteCount++;
}
}
if (quoteCount % 2 != 0)
{
parameterPosition = commandText.IndexOfAny(matchParameterIdentifiers, parameterPosition + 1);
continue;
}
}
break;
}
return parameterPosition;
}