长时间运行的SP永远不会使用sqlCommand结束

时间:2014-02-04 11:03:05

标签: sql-server vb.net

我的SQL Server数据库中有一个非常昂贵的存储过程。从SQL Server Managment Studio启动它需要几分钟。但我无法使用SqlCommand通过代码启动它。

我有这段代码:

spExecQuery = "EXEC [schema].[storedName]" 

如果我使用这个vb.NET代码段:

Using sqlCmd As SqlCommand = New SqlCommand(spExecQuery, conn)
    sqlCmd.ExecuteNonQuery()
End Using

脚本以“Timeout expired”错误结束。但如果我这样做:

Using sqlCmd As SqlCommand = New SqlCommand(spExecQuery, conn)
    sqlCmd.CommandTimeout = 0
    sqlCmd.ExecuteNonQuery()
End Using

脚本永远不会结束(它至少运行2小时)...我错过了什么?谢谢。

3 个答案:

答案 0 :(得分:2)

首先需要指定它是存储过程:

Using sqlCmd As SqlCommand = New SqlCommand(spExecQuery, conn)
    sqlCmd.CommandType = CommandType.StoredProcedure
    sqlCmd.CommandTimeout = 0
    sqlCmd.ExecuteNonQuery()
End Using

你也可以使用QueueUserWorkItem让方法异步运行,然后你就不需要等到它完成了:

Public Shared Sub ExecuteStoredProcedureAsync()
    Threading.ThreadPool.QueueUserWorkItem(
        New Threading.WaitCallback(AddressOf ExecuteStoredProcedure)
        )
End Sub

Private Shared Sub ExecuteStoredProcedure(threadState As Object)
    Dim sw = New Stopwatch()
    sw.Start()
    Try
        ' add code or call of long running method here '
        Log.WriteInfo(String.Format("ExecuteStoredProcedure(async call) executed successfully, execution-time: {0}.", sw.Elapsed))
    Catch ex As Exception
        Log.WriteError(String.Format("Exception in ExecuteStoredProcedure (async call), execution-time: {0}.", sw.Elapsed))
    End Try
End Sub

答案 1 :(得分:0)

如果指定 CmdType ,它应该有效。

如果仍然无效,请尝试使用 SqlDataReader

 cmd.Connection = conn
 cmd.CommandType = CommandType.StoredProcedure
 cmd.CommandText = "proc_name"

 Dim dr As SqlDataReader = cmd.ExecuteReader

答案 2 :(得分:0)

尝试将命令类型添加到sqlcommand

sqlCmd.CommandType = CommandType.StoredProcedure