如何使用vb.net更改存储过程

时间:2016-10-04 15:29:38

标签: sql-server vb.net stored-procedures alter

我正在创建一个应用程序,允许我一次将存储过程部署到多个数据库。代码首先检查存储过程是否已存在于目标数据库中。如果它已经存在,它应该改变程序,如果它不存在,它应该创建程序。这是代码的样子:

Imports System.Data.SqlClient
Imports Microsoft.SqlServer.Management.Smo
Imports Microsoft.SqlServer.Management.Common

'----------------------------------------------
' First I create the stored procedure object
'----------------------------------------------
Dim srv As New Server(serverName)
Dim db  As Database = srv.Databases(databaseName)
Dim sp  As New StoredProcedure(db, procedureName)

Try
    sp.TextMode               = False
    sp.AnsiNullStatus         = True
    sp.QuotedIdentifierStatus = True

    ' Add Parameters
    For i As Integer = 0 to parameterList.Items.Count - 1
        Dim nextParam As New StoredProcedureParameter(sp, parameterList.Items(i), typeList.items(i))
        sp.Parameters.Add(nextParam)
    Next

    ' Add the body
    sp.TextBody = procedureText
Catch ex As Exception
    Exit Sub
End Try

'---------------------------------------------------------------------
' Then I check to see if the procedure already exists in the database
'---------------------------------------------------------------------
Dim sqlConnection As New SqlConnection(connectionString)
Dim cmd           As New SqlCommand
Dim reader        As SqlDataReader
Dim procsInDB     As New List(Of String)

cmd.CommandType = CommandType.Text
cmd.Connection  = sqlConnection
cmd.CommandText = "SELECT CAST(routine_name AS VARCHAR(200)) FROM information_schema.routines WHERE routine_type = 'PROCEDURE'"

sqlConnection.Open()
reader = cmd.ExecuteReader()

If reader.HasRows then
    Do While reader.Read()
        procsInDB.Add(reader.GetString(0))
    Loop
End If

'-------------------------------------------------------------
' Now I run either the Create() or Alter() based on whether
' the stored procedure already exists in the database
'-------------------------------------------------------------
If procsInDB.IndexOf(sp.Name) = -1 then
    sp.Create()
Else
    sp.Alter()
End If

当我对没有存储过程的数据库运行此代码时,它调用sp.Create()命令并且它工作正常。当我对已经有程序的数据库运行代码时,它调用sp.Alter()但它给了我这个错误:

  

Microsoft.SqlServer.Management.Smo.InvalidSmoOperationException:您无法对状态为“创建”中的对象执行操作Alter。

据我所知,我收到此错误是因为我声明的sp对象尚未调用Create()方法,因此它无法解决用Alter()方法改变。但是如果存储过程已经存在,我不想创建它,我只想改变它。有谁知道这样做的方法?

0 个答案:

没有答案