Hi @MannySo ,
Not sure if I understood your question correctly, if there is a misunderstanding please point it out.
Delete Table: If the table exists and the user input is "yes", the table is deleted.
Create Table: If the table does not exist and the user input is "no", a new table is created.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connectionString As String = "Your_Connection_String_Here"
Dim tableName As String = "YourTableName"
Dim userInput As String = TextBox1.Text.ToLower()
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim tableExists As Boolean = False
Dim checkTableQuery As String = $"IF OBJECT_ID('{tableName}', 'U') IS NOT NULL SELECT 1 ELSE SELECT 0"
Using checkCommand As New SqlCommand(checkTableQuery, connection)
tableExists = Convert.ToBoolean(checkCommand.ExecuteScalar())
End Using
If tableExists AndAlso userInput = "yes" Then
Dim dropTableQuery As String = $"DROP TABLE {tableName}"
Using dropCommand As New SqlCommand(dropTableQuery, connection)
dropCommand.ExecuteNonQuery()
End Using
MessageBox.Show("Table deleted.")
ElseIf Not tableExists AndAlso userInput = "no" Then
Dim createTableQuery As String = $"CREATE TABLE {tableName} (ID INT PRIMARY KEY, Name NVARCHAR(50))"
Using createCommand As New SqlCommand(createTableQuery, connection)
createCommand.ExecuteNonQuery()
End Using
MessageBox.Show("Table created.")
Else
MessageBox.Show("No action taken.")
End If
End Using
End Sub
Best Regards.
Jiachen Li
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.