以下は、procudere を作成するためのすぐに使用できるサブルーチンです。
Public Shared Sub CreateSP(ByVal usp As String, ByVal sender As Object, ByVal e As System.EventArgs)
Dim RetValue As Boolean = False
Try
DBConnection("SQLConn", "SQLUSER", "master", False, sender, e)
Select Case SQLConn.State
Case ConnectionState.Open
MASQLComm = New SqlCommand("CREATE PROCEDURE [dbo].[" & usp & "]" & _
NewLine & " ( " & _
NewLine & "@DBName varchar(50) ) AS " & NewLine & _
"BEGIN_TRY: " & NewLine & " SET QUOTED_IDENTIFIER ON;" & NewLine & " SET NOCOUNT ON; " & _
NewLine & "DECLARE " & _
NewLine & "@ErrMsg nvarchar(4000), " & _
NewLine & "@CreateSdb nvarchar(4000)" & _
NewLine & "SET @CreateSdb =('CREATE DATABASE ' + @DBName )" & _
NewLine & "BEGIN_CATCH:" & NewLine & "SELECT ERROR_MESSAGE() as ErrorMessage;" & _
NewLine & "SELECT @ErrMsg = ERROR_MESSAGE()" & _
NewLine & "EXEC sp_executesql @CreateSdb" & _
NewLine & "RAISERROR (@ErrMsg,2,1)" & _
NewLine & "Return 0" & NewLine & "END_CATCH:" & NewLine & "Return 1" & NewLine & "END_TRY: ", SQLConn)
If MASQLComm.Connection.State = ConnectionState.Open Then
MASQLComm.ExecuteNonQuery()
Else
MASQLComm.Connection.Open()
MASQLComm.ExecuteNonQuery()
End If
End Select
Success = True
Catch ex As Exception
MessageBox.Show(ex.Message, "Class 'DB_Access' CreateSP ", MessageBoxButtons.OK, MessageBoxIcon.Stop)
Success = False
End Try
MASQLComm.Connection.Close()
End Sub
上記の手順を実行するためのコードは次のとおりです。
Public Shared Sub RunSP(ByVal DrivePath As String, ByVal DBname As String, ByVal sender As Object, ByVal e As System.EventArgs)
Try
DBConnection("SQLConn", "SQLUSER", "master", False, sender, e)
MASQLComm = New SqlCommand("EXEC dbo." & procName & " '" & DBname & " '", SQLConn)
MASQLComm.ExecuteNonQuery()
MASQLComm.ExecuteNonQuery()
MASQLComm = New SqlCommand("ALTER DATABASE " & DBname & " SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE", SQLConn)
MASQLComm.ExecuteNonQuery()
Success = True
Catch qx As SqlException
MessageBox.Show(qx.Message, "Class 'NainClass' Run Stored Procdure", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
Success = False
End Try
MASQLComm.Connection.Close()
End Sub
SQLconn 接続文字列のコードは次のとおりです。
If Not CBool(SQLConn.State) Then
SQLConn.ConnectionString = "server=" & ServNameKeyValue & "; Uid=" & cUserName & "; Pwd=" & cUserPass & "; database=" & DBname
SQLConn.Open()
Else
SQLConn.Close()
SQLConn.ConnectionString = "server=" & ServNameKeyValue & "; Uid=" & cUserName & "; Pwd=" & cUserPass & "; database=" & DBname
SQLConn.Open()
End If