SQLDatareader via CLR not returning SQL Message right way

被刻印的时光 ゝ 提交于 2019-12-13 03:31:16

问题


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
    )

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/3356481/sqldatareader-via-clr-not-returning-sql-message-right-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!