Domanda

I wrote this procedure in a site. it take a string as input parameter(user name) and looks into the related table to find out it's record and return the "ID" field as output of procedure. this work fine but there's one (major) problem, which is when it take a input in other English language, it can't find the target record and return "-1" as output. The visitors use Persian language and i observed it in my SQLserver. The collation is "Persian_100_CI_AI" and my string fields are "nvarchar". what should i do to solve this problem? i'm using SQL-Server 2008.

thanks a lot

protected int GetThisUserID(string uname)
{
    string returnvalue = "";
    int returnintegervalue = -1;
    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["OldEagleConnectionString"].ToString());
    try
    {
        //SqlCommand command = new SqlCommand("SELECT [ID] FROM [Customers] WHERE ([Uname] = '" + User.Identity.Name.ToString() + "'", connection);
        //SqlCommand command = new SqlCommand("SELECT * FROM [Customers] WHERE ([Uname] = '" + User.Identity.Name.ToString() + "')", connection);
        SqlCommand command = new SqlCommand("SELECT * FROM [Customers] WHERE ([Uname] = '" + uname + "')", connection);

        connection.Open();
        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                returnvalue = reader["ID"].ToString();

                returnintegervalue = Int32.Parse(returnvalue);
            }
        }
    }
    catch (SqlException ex)
    {
        Response.Write(ex.Message.ToString());
        returnvalue = ex.Message.ToString();
    }
    finally
    {
        connection.Close();
        SqlConnection.ClearPool(connection);
    }
    return returnintegervalue;
}
È stato utile?

Soluzione

I hate to answer my own question but here it is:

have to add a N in select command, just like this:

SqlCommand command = new SqlCommand("SELECT * FROM [Customers] WHERE ([Uname] = N'" + uname + "')", connection);

problem solved!

Without the N, the string is taken to be a varchar, and the conversion loses characters outside of that supported by the varchar encoding of the database.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top