Click here to Skip to main content
15,891,431 members
Articles / Programming Languages / C#
Tip/Trick

Turn String Parameters to VARCHAR from NVARCHAR

Rate me:
Please Sign up or sign in to vote.
4.23/5 (9 votes)
28 Oct 2015CPOL 21.2K   2   3
If your database is ANSI then make your string parameters match

Introduction

When writing the old style (hand coded dirty SQL queries), it is common to add parameters to your command using the Parameters.AddWithValue method.  However as .NET strings are unicode, this will make the parameter be passed as an NVARCHAR

If you are running against a database that has all of its columns specified as ANSI strings using the data type VARCHAR, then this will result in a significant performance penalty as the data access layer will need to perform a data type translation as part of the query.

To prevent this, you can explicitly set all your string parameters to ANSI.

Background

Ideally, you should have all your database using NVARCHAR fields if you want to do business in a global marketplace, but often legacy systems are not built that way.

Using the Code

The following static method "cleans up" the command so that all string parameters are passed as ANSI (VARCHAR). 

C#
/// <summary>
/// For every command parameter in the command, if its type is NVARCHAR turn it to VARCHAR instead
/// so that indexes can be used
/// </summary>
/// <param name="sourceCommand">
/// The source command with parameters
/// </param>
public static void CleanCommandStringParameters(SqlCommand sourceCommand)
{
    if (null != sourceCommand)
    {
        if (null != sourceCommand.Parameters)
        {
            foreach (SqlParameter  param in sourceCommand.Parameters )
            {
                if (param.SqlDbType == SqlDbType.NVarChar)
                {
                    param.SqlDbType = SqlDbType.VarChar;
                }
                if (param.SqlDbType == SqlDbType.NChar)
                {
                    param.SqlDbType = SqlDbType.Char;
                }
            }
        }
    }
}

History

  • 2015-10-28: Created

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Ireland Ireland
C# / SQL Server developer
Microsoft MVP (Azure) 2017
Microsoft MVP (Visual Basic) 2006, 2007

Comments and Discussions

 
GeneralReason for performance penalty Pin
robert204829-Oct-15 4:41
robert204829-Oct-15 4:41 
QuestionHow to used this function in EF ? Pin
Member 1108038428-Oct-15 19:48
Member 1108038428-Oct-15 19:48 
AnswerRe: How to used this function in EF ? Pin
Duncan Edwards Jones28-Oct-15 21:49
professionalDuncan Edwards Jones28-Oct-15 21:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.