views:

39

answers:

2

I execute the following code via CLR, is there a reason why the message is not printed to the SQL Server, does it need to wait until the Stored Procedure returns all the rows (there is about 7 Billion rows to return)

    SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "spCommand_Select_Rows_For_Delete";
        cmd.CommandTimeout = 41600;

        SqlDataReader reader = cmd.ExecuteReader();
        try
        {
            string strSQL = "";
            SqlContext.Pipe.Send(DateTime.Now.ToString() + " - Started working with ProductTable");

            while (reader.Read())
            {
                strSQL = "DELETE FROM ProductTable WHERE ProductId = " + reader["ProductId"].ToString();

                SqlCommand cmdDelete = new SqlCommand(strSQL, conn);

                cmdDelete.Connection = conn;
                cmdDelete.CommandTimeout = 20800;
                cmdDelete.ExecuteNonQuery();
            }

            SqlContext.Pipe.Send(DateTime.Now.ToString() + " - Completed working with ProductTable");
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }

My Stored Procedure:

SELECT ProductId FROM ProductTable
    WHERE ProductInfoId IN
    (
    SELECT ProductInfoId from DeletedProducts
    )
+2  A: 

Here's how you delete 7 billion rows using a nice set based operation. You don't abuse iterate through a datareader in CLR.

 SELECT 'Starting'
 WHILE ROWCOUNT <> 0
    DELETE TOP (1000000) P
    FROM  ProductTable P
    WHERE EXISTS (
        SELECT * from DeletedProducts DP WHERE P.ProductInfoId = DP.ProductInfoId
    )

For more, see this question Bulk DELETE on SQL Server 2008

But to answer your question, yes, SQL Server will not PRINT (which is what you're doing) immediately

gbn
Will this break out of the table as soon as it hits the top (1000000) instead of continuing to scan the whole table?
RPS
@RPS: It will delete in batches of 1000000 because of WHILE (now I fixed the typo)
gbn
@gbn: Will this not cause the SQL LOG to grow extremely large?
RPS
Delete 7 billion rows 1 by 1, or in 7000 batches is irrelevant pretty much
gbn
@gbn: I want delete many rows, but i dont want to eat a lot of disk space and also not take weeks to delete.
RPS
+1  A: 

You could probably use SqlContext.Pipe.ExecuteAndSend with RAISERROR WITH NOWAIT to do what you want about the message.

But I'm with gbn's answer about not needing the CLR for batched deletes.

Cade Roux