SQL查询执行顺序错误

时间:2016-07-09 15:04:02

标签: c# sql visual-studio

开始学习sql并遇到查询问题。我有 - 2表日历和活动和FK表DateActivities。有2个简单的列表日历与日期和活动。我希望能够通过单击按钮在所选日期通过文本框输入新活动。但是,当我这样做时,我得到一个查询错误。谢谢你的帮助。

private void btnAddToDate_Click(object sender, EventArgs e)
    {
        string query = "DECLARE @ActivitiesId TABLE (Id INT) " + 
                       "INSERT INTO Activities (Name) " +
                       "OUTPUT INSERTED.ID INTO @ActivitiesId Id(Id) " +
                       "VALUES (@ActivitiesName) " +
                       "INSERT INTO DateActivities VALUES (@CalendarId, @ActivitiesId)";

        using (connection = new SqlConnection(connectionString))
        using (SqlCommand command = new SqlCommand(query, connection))
        {
            connection.Open();
            command.Parameters.AddWithValue("@ActivitiesName", textDate.Text);
            command.Parameters.AddWithValue("@CalendarId", listCalendar.SelectedValue);
            command.ExecuteNonQuery();
        }

        FillCalendar();
        FillActivities();
    }

2 个答案:

答案 0 :(得分:1)

您正在尝试执行多个语句,因此需要将它们与;分隔为行终止符,如下所示,否则它将被视为要执行的单个语句。如果您只是在SSMS中复制/粘贴语句块,您将收到相同的错误。

"DECLARE @ActivitiesId TABLE (Id INT); " + 
                       "INSERT INTO Activities (Name) " +
                       "OUTPUT INSERTED.ID INTO @ActivitiesId Id(Id) " +
                       "VALUES (@ActivitiesName); " +
                       "INSERT INTO DateActivities VALUES (@CalendarId, @ActivitiesId)"

您最好将其关闭到存储过程,而不是作为adhoc查询运行。

答案 1 :(得分:0)

您要将整个表格插入DateActivities的列值中,这显然是错误的并且会失败,您需要使用另一个变量来保存ActivityId,然后将其插入,请参阅下文:< / p>

"DECLARE @ActivitiesId TABLE (Id INT)
 DECLARE @ActivityId INT " + 
                       "INSERT INTO Activities (Name) " +
                       "OUTPUT INSERTED.ID INTO @ActivitiesId Id(Id) " +
                       "VALUES (@ActivitiesName) " +
                       "SELECT @ActivityId = Id from @ActivitiesId"
                       "INSERT INTO DateActivities VALUES (@CalendarId, @ActivityId)";