请看下面的子程序:
Private Sub UpdateGrade(ByVal studentID As Integer, ByVal grade As String)
Dim objCommand As SqlCommand
Dim objCon As SqlConnection
Dim id As Integer
Dim _ConString As String
Try
_ConString = ConfigurationManager.ConnectionStrings("TestConnection").ToString
objCon = New SqlConnection(_ConString)
objCommand = New SqlCommand("DECLARE @StudentID INT " & _
"DECLARE @Grade char(1) " & _
"SET @Grade = '" & grade & "'" & _
"SET @StudentID = '" & studentID & "'" & _
"If @Grade=1 " & _
"begin " & _
"update Student SET Grade = 'A' WHERE StudentID = @StudentID " & _
"end " & _
"Else If @Grade=2 " & _
"begin " & _
"update Student SET Grade = 'B' WHERE StudentID = @StudentID " & _
"end " & _
"If @Grade=3 " & _
"begin " & _
"update Student SET Grade = 'C' WHERE StudentID = @StudentID " & _
"end " & _
"Else If @Grade=4 " & _
"begin " & _
"update Student SET Grade = 'D' WHERE StudentID = @StudentID " & _
"end")
objCommand.Connection = objCon
objCon.Open()
objCommand.ExecuteNonQuery()
Catch ex As Exception
Throw
Finally
End Try
将 Command.CommandText 设置为 TSQL 语句有什么问题吗?TSQL 看起来像这样(为了便于阅读):
DECLARE @StudentID INT
DECLARE @Grade char(1)
SET @Grade =
SET @StudentID =
If @Grade=1
begin
update Student SET Grade = 'A' WHERE StudentID = @StudentID
end
Else If @Grade=2
begin
update Student SET Grade = 'B' WHERE StudentID = @StudentID
end
If @Grade=3
begin
update Student SET Grade = 'C' WHERE StudentID = @StudentID
end
Else If @Grade=4
begin
update Student SET Grade = 'D' WHERE StudentID = @StudentID
end
在 while 循环中有对 UpdateGrade 的调用。while 循环遍历 500 万学生。请注意,实时系统对此更加复杂,因此我提供了上面的代码以进行说明。
过去我在从 .NET 代码调用存储过程时遇到过问题,XACT_ABORT 解决了这个问题。