9

I have an insert query to execute from within a C# against a SQL Server database.

The column I am inserting to is of type nvarchar.

the data I am inserting to that column is non-english.

Is it sufficient for me to use AddWithValue in order to pass the non-english data to the server? like this example:

string dogName = "עברית";
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (SqlCommand command = new SqlCommand("INSERT INTO Dogs1(Name) VALUES @Name", connection))
    {
    command.Parameters.AddWithValue("Name", dogName);
    command.ExecuteNonQuery();
    }
}

Or must I use the N prefix to declare it unicode? like it says so here.

Bogdan Sahlean
  • 19,233
  • 3
  • 42
  • 57
kroiz
  • 1,722
  • 1
  • 27
  • 43

2 Answers2

7

If I am understanding the question correctly, you can explicitly set the SqlCommand parameter to be a specific data type. You will be able to set it to be nvarchar as shown by the following link: http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx

This below code snippet is taken directly from MSDN:

SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;

This uses an explicitly created SqlParameter instance, but it is the same idea by indexing the SqlParameterCollection of the SqlCommand instance.

  • That is good to know, but must I go into all this trouble for each parameter? All this extra work lower the readability of the code and I really would like to go without it if I can. – kroiz Sep 28 '11 at 08:08
4

I believe the link at the bottom is only really talking about values within SQL itself.

As far as I'm aware, the code you've got should be absolutely fine - otherwise there'd be no way of specifying Unicode text.

Of course, it's probably worth validating this - but I'd be very surprised if it didn't work.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • please see my answer. I agree that it'll probably work as a `string` will implicitly be nvarchar, but there is a way to explicitly call what the datatype is. –  Sep 26 '11 at 00:22