I want to use Windows Forms and C# to implement a Database application which consists of the following tables:
Student table:
CREATE TABLE [dbo].[Student]
(
[Id] INT NOT NULL,
[Name] NVARCHAR(50) NOT NULL,
[MyId] AS ('S' + RIGHT('00' + CONVERT([varchar](5), [Id]), (2))) PERSISTED,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Class table:
CREATE TABLE [dbo].[Class]
(
[Id] INT NOT NULL,
[Teacher] NVARCHAR(50) NOT NULL,
[Grade] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
StudentClassCombo:
CREATE TABLE [dbo].[StudentClassCombo]
(
[ClassID] INT NOT NULL,
[StudentID] INT NOT NULL,
CONSTRAINT [ClassFK]
FOREIGN KEY ([ClassID]) REFERENCES [dbo].[Class] ([Id]),
CONSTRAINT [StudentFK]
FOREIGN KEY ([StudentID]) REFERENCES [dbo].[Student] ([Id])
);
I have a Windows forms interface through which I can assign students to classes.
I want to ensure that when the a student that has already been assigned to a class is re-assigned to a different class. the previous student-class assignment should be overwritten with the new one. In the case above, if Student ID 1 is already assigned to Class ID 1. But if the user decides to re-assign Student ID 1 to Class ID 2, the existing StudentClassCombo entry of 1-1 should be changed to 1-2.
I have written the following code to perform this update but I am encountering an exception:
string UpdateQuery = @"UPDATE dbo.StudentClassCombo SET"
+ " Class.ID as ClassId, Student.Id as StudentId FROM dbo.Class, dbo.Student" +
" WHERE Class.Grade=@Grade and Student.Name LIKE @StudentName";
using (connection = new SqlConnection(connectionString))
using (SqlCommand Insertcmd = new SqlCommand(UpdateQuery, connection))
{
connection.Open();
Insertcmd.Parameters.Add("@Grade", SqlDbType.Int);
Insertcmd.Parameters.Add("@StudentName", SqlDbType.NVarChar, 50);
foreach (ListViewItem eachItem in StudentsList.CheckedItems)
{
Insertcmd.Parameters["@Grade"].Value = int.Parse(ClassNames.Text);
Insertcmd.Parameters["@StudentName"].Value = eachItem.SubItems[1].Text.ToString();
Insertcmd.ExecuteNonQuery();
}
connection.Close();
}
The exception I am seeing now is as follows:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near the keyword 'as'.
How should I update the StudentClassCombo entries?

updatestatement yousetcolumn values with=, notas. Are you sure thatUpdateQueryis what you want to execute forInsertcmd?