Search code examples
sql-server-2005devexpressiasyncresult

SQL Syntax error when using SQLCommand.EndExecuteNonQuery


I'm trying to run two SQL statements (MSSQL 2005), asynchronously in a background worker. However, when I call the EndExecuteNonQuery method on the first SqlCommand I get a 'SQL syntax error near' error.

Here is my code:

try
{
    SqlCommand sqlCmd = uow.DataLayer.CreateCommand() as SqlCommand;
    sqlCmd.CommandText = "DELETE FROM dbo.EligibilityRecordKeyValue WHERE EligibilityRecord IN " +
    "(SELECT EligibilityRecord FROM dbo.EligibilityRecord WHERE Organization = '" + map.Organization.Oid + "')";
    IAsyncResult result = sqlCmd.BeginExecuteNonQuery();
    while (!result.IsCompleted)
    {
        worker.ReportProgress(0, "Deleting existing record keys");
        System.Threading.Thread.Sleep(200);
    }
    count = sqlCmd.EndExecuteNonQuery(result);
}
catch (SqlException ex)
{
}
catch (InvalidOperationException ex)
{
}
finally
{
    worker.ReportProgress(2, String.Format("Existing {0} records keys deleted.", count));
}

try
{
    SqlCommand sqlCmd = uow.DataLayer.CreateCommand() as SqlCommand;
    sqlCmd.CommandText = "DELETE FROM dbo.EligibilityRecord WHERE Organization = '" +      map.Organization.Oid + "'";
    IAsyncResult result = sqlCmd.BeginExecuteNonQuery();
    while (!result.IsCompleted)
    {
        worker.ReportProgress(0, "Deleting existing records");
        System.Threading.Thread.Sleep(200);
    }
    count = sqlCmd.EndExecuteNonQuery(result);
}
catch (SqlException ex)
{
}
catch (InvalidOperationException ex)
{
}
finally
{
    worker.ReportProgress(5, String.Format("Existing {0} records deleted.", count));
}

It fails on the first count = sqlCmd.EndExecuteNonQuery(result);


Solution

  • Ok, adding WAITFOR DELAY's to both SQL commands seems to have resolved the issue.

    sqlCmd.CommandText = String.Format("WAITFOR DELAY '00:00:05'; DELETE FROM dbo.EligibilityRecordKeyValue WHERE EligibilityRecord IN " + 
                        "(SELECT EligibilityRecord FROM dbo.EligibilityRecord WHERE Organization = '{0}')", map.Organization.Oid);
    
    sqlCmd.CommandText = String.Format("WAITFOR DELAY '00:00:05'; DELETE FROM dbo.EligibilityRecord WHERE Organization = '{0}'", map.Organization.Oid);
    

    Anyone know why this happens?