Search code examples
c#sql-server-ce

Using NCHAR to get special characters in C#


I'm implementing a SQL Server CE database in my application and trying to convert some of the SQL queries into the code. I have this statement:

INSERT INTO Unit (unitTypeID, label) VALUES (@unitTypeID, 'm/s' + NCHAR(0x00B2));

My code in C# looks like this:

            string value = @"'m/s' + NCHAR(0x00B2)";
            cmdString = "INSERT INTO Unit (unitTypeID, label) VALUES (@guid, @value)";
            cmd = new SqlCeCommand(cmdString, connection);
            cmd.Parameters.Add("@guid", guid).SqlDbType = SqlDbType.UniqueIdentifier;
            cmd.Parameters.Add("@value", value).SqlDbType = SqlDbType.NText;
            cmd.ExecuteNonQuery();

The NCHAR(0x00B2) is a superscript 2. How do I replicate this functionality in C#? I'd rather not paste ² into the code because I use several special characters in this database.


Solution

  • You can't pass expressions as parameters - only values (in fact, that's one of the big reasons to use parametrized queries in the first place). So you're literally passing the string '''m/s'' + NCHAR(0x00B2)' - quite different from what you're trying to do.

    One way to handle this would be by using escape characters in the string: "m/s\u00B2".

    To improve readability, I'd suggest keeping those special characters as constants, e.g.:

    /// <summary>Superscript two ("²").</summary>
    const string SuperscriptTwo = "\u00B2";
    
    ...
      var val = "m/s" + SuperscriptTwo;
    ...