Reputation: 680
I am kinda new to C# and .NET applications. I work with visual studio and have this table :
CREATE TABLE [dbo].[Table] (
[Id] INT NOT NULL,
[Meno] NVARCHAR (50) NULL,
[Datum] DATETIME NULL,
[Cas] INT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
And now I have a simple insert
public void NahrajSkore(string cas)
{
using (var con = new SqlConnection(cns))
{
con.Open();
var inset = new SqlCommand("Insert into Table values(@name,@date,@res)", con);
inset.Parameters.Add("@name", SqlDbType.VarChar);
inset.Parameters.Add("@date", SqlDbType.DateTime);
inset.Parameters.Add("@res", SqlDbType.Int);
inset.Parameters["@name"].Value = _hrac.MenoHraca;
inset.Parameters["@date"].Value = DateTime.Today;
inset.Parameters["@res"].Value = int.Parse(cas);
inset.ExecuteNonQuery();
}
}
BUt this method gives me error :
Incorrect syntax near the keyword 'Table'
What am I doing wrong ?
Upvotes: 0
Views: 190
Reputation: 143
Please try to use the different name for the table to resolve this issue.
For ex:
using(var inset = new SqlCommand("Insert into Student values(@name,@date,@res)", con))
Upvotes: 0
Reputation: 98750
Table
is a reserved keyword in T-SQL.
You should use it with square brackets like [Table]
If a reserved word is already in use, you can avoid error messages by surrounding each occurrence of the word with brackets (
[ ]
). However, the best solution is to change the name to a nonreserved word.
You can use using
statement for SqlCommand
as well and you can define and add values of your parameters in a single line like;
using (var con = new SqlConnection(cns))
{
using(var inset = new SqlCommand("Insert into [Table] values(@name,@date,@res)", con))
{
inset.Parameters.Add("@name", SqlDbType.VarChar).Value = hrac.MenoHraca;
inset.Parameters.Add("@date", SqlDbType.DateTime).Value = DateTime.Today;
inset.Parameters.Add("@res", SqlDbType.Int).Value = int.Parse(cas);
con.Open();
inset.ExecuteNonQuery();
}
}
Also specifying column names in your SqlCommand
is always recommended like;
"Insert into [Table](NameColumn, DateColumn, ResColumn) values(@name,@date,@res)"
Upvotes: 4
Reputation: 8867
I believe Table
is a reserved word in SQL :)
Try using another name for your table or use [Table]
instead.
Upvotes: 1