user2224376
user2224376

Reputation: 397

C# local database update error

The issue is that I'm trying to write into a table called Login. It has a few columns, there's a column with no data in (null) that I'm trying to insert / update the column is SuperSecretKey - nvarchar(100).

Heres the code:

public void InsertSecretKey(String SuperKey, int IDKey)
{
    conn = new SqlCeConnection(@"Data Source=|DataDirectory|\Database1.sdf");
    conn.Open();

    SqlCeCommand cmd = new SqlCeCommand();
    cmd.CommandText = "UPDATE Login SET SuperSecretKey = @SuperKey WHERE Key=@IDKEY;";
    cmd.Connection = conn;

    cmd.Parameters.AddWithValue("@SuperKey", SuperKey);
    cmd.Parameters.AddWithValue("@IDKey", IDKey);

    cmd.ExecuteNonQuery();
    conn.Close();
}

Here's the error:

There was an error parsing the query.
[ Token line number = 1,Token line offset = 51,Token in error = Key ]

Any help? Thanks!

Upvotes: 0

Views: 98

Answers (2)

RobIII
RobIII

Reputation: 8821

Key is a reserved word. The error is pretty specific: offset = 51 => at position 51 there's the word key. It actually tells you: Token in error = Key.

You need to escape it, e.g. [key]. It is a good practice to escape all your fieldnames, tables etc.:

cmd.CommandText = "UPDATE [Login] SET [SuperSecretKey] = @SuperKey WHERE [Key]=@IDKEY;";

What isn't a reserved keyword in the current version of SQL Server may be in a new/future release1. Most ORM's etc. that generate ("dynamic") queries escape these values by default, just to be "on the safe side".

1 Even if a keyword isn't on that list currently, it may be added in a future-future release. You'll probably be safe with names like CustomerId and MyVerySpecificName but generic words like Key (you just found that out), GUID, Version or Descending, though currently not reserved, are just not (future-)safe to use.

Upvotes: 5

meda
meda

Reputation: 45490

Key is a reserverd keyword

use brackets to escape it [key]

For the full list check Reserved Keywords (Transact-SQL)

Upvotes: 3

Related Questions