-1

显然,插入列表包含的项目多于所选值的数量,但似乎看不到这种情况。通过观察它们是相同的,除非我遗漏了什么?

   public static DateTime CreateMedicationDispenseLocationHistory( int medicationDispenseID, int locationID, int staffID, DateTime date )
    {
        SqlConnection connection = new SqlConnection( Utilities.DBConnectionString() );
        connection.Open();

        CreateMedicationDispenseLocationHistory( medicationDispenseID, locationID, staffID, date, connection, null );

        connection.Close();
        connection.Dispose();

        return date;
    }

    public static DateTime CreateMedicationDispenseLocationHistory( int medicationDispenseID, int locationID, int staffID, DateTime date, SqlConnection connection, SqlTransaction transaction )
    {
        Locations location = new Locations();
        MedicationList medication = new MedicationList();
        StringBuilder sqlString = new StringBuilder();

        SqlCommand command;

        sqlString.Append("INSERT INTO [MedicationDispenseLocationHistory] (");
        sqlString.Append("MedicationDispenseID, " );
        sqlString.Append("LocationID, " );
        sqlString.Append("StaffID, " );
        sqlString.Append("DateTimeStamp" );
        sqlString.Append(") SELECT SCOPE_IDENTITY();");

        command = new SqlCommand( sqlString.ToString(), connection );
        if( ( transaction != null ) ) command.Transaction = transaction;

        command.Parameters.Add( "@MedicationDispenseID", SqlDbType.Int ).Value = medication.MedicationDispenseID;
        command.Parameters.Add( "@LocationID", SqlDbType.Int ).Value = location.LocationID;
        command.Parameters.Add( "@StaffID", SqlDbType.Int, 500 ).Value = Helper.GetValue( GlobalVariables.loggedInStaff.StaffID );
        command.Parameters.Add( "@DateTimeStamp", SqlDbType.DateTime ).Value = Helper.GetDBDateValue(DateTime.Now);
        //command.Parameters.Add("@stopDate", SqlDbType.DateTime).Value = Helper.GetValue(medicationDispense.StopDate);
        medication.MedicationDispenseID = Convert.ToInt32( command.ExecuteScalar() );

        return date;
    }
4

1 回答 1

3

在 INSERT INTO 语句的末尾添加分号

  sqlString.Append("); SELECT SCOPE_IDENTITY();");

否则,以下SELECT SCOPE_IDENTITY()将被解释为 INSERT 的 SELECT 值列表

插入.......选择

完成答案(感谢以下评论的作者)
不要忘记为您的参数添加值占位符

  sqlString.Append(") VALUES (@MedicationDispenseID,@LocationID,@StaffID,@DateTimeStamp);");
  sqlString.Append("SELECT SCOPE_IDENTITY();");
于 2013-07-30T15:58:20.010 回答