Link to home
Start Free TrialLog in
Avatar of Seamie_
Seamie_

asked on

How do I use VB .Net to delete a table in SQL Server?

Hi Experts,

The code attached below is crashing at the point marked <=***

Where in the previous code have I gone wrong?

Many thanks in advance,

Seamie

    Public Function DropDatabase(ByVal connString As String, ByVal sDBName As String) As Boolean
        Dim cn As New SqlConnection(connString)
        Try
            cn.Open()
            'Dim cmdDrop As New SqlCommand("DROP DATABASE " & sDBName, cn) [my note: I've alternated between this line and the next by remarking the other one out]
            Dim cmdDrop As New SqlCommand("DROP DATABASE " & sDBName)
            cmdDrop.ExecuteNonQuery()                                                              <=***
            WriteToFile("Setup", "Database Deleted")
        Catch ex As Exception
            MsgBox("Encountered an Error in deleting the database: " & sDBName & vbCrLf & "It is important that you contact the SQL Server Administrator and tell him/her that this database needs to be deleted!", MsgBoxStyle.Critical)
            WriteToFile("Setup", "Database not deleted (" & sDBName & ")" & vbCrLf & "Connection String= " & connString)
        Finally
            cn.Close()
        End Try
    End Function
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Hi Seamie_,

What is the error message?

Is the user (used in your connection string) is allowed to drop database?

Your second declaration does not have any connection to run against.

Cheers!
Avatar of Seamie_
Seamie_

ASKER

Hi Emoreau

Error Message:=> ExecuteNonQuery: Connection Property has not been initialised

Thanks

Seamie
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
you must use the connection object along with the Command object, like this:

 cn.Open()
            'Dim cmdDrop As New SqlCommand("DROP DATABASE " & sDBName, cn) [my note: I've alternated between this line and the next by remarking the other one out]
            Dim cmdDrop As SqlCommand = New SqlCommand("DROP DATABASE " & sDBName, cn)
            cmdDrop.ExecuteNonQuery()                                                              <=***
            WriteToFile("Setup", "Database Deleted")
        Catch ex As Exception

when you say you have alternated between the two forms, what do you get with this syntax?

AW
Avatar of Seamie_

ASKER

Yup, it worked thanks