1

I am creating a 'delete user account' button for my vb.net app. There may be some tables the user created, which need to be deleted along with the user's account. Any table the user created will be named with the user's id and a number. ex: 'sam_21', 'sam_45'. how can I drop all tables that have start with 'sam_"?

would it be something like:

 dim userID = Users.Identity.Name
 cmd = New SqlCommand("DROP table_name WHERE table_name LIKE @userId")
 cmd.Parameters.AddWithValue("@userId", userID & "_%")
 dc.Open()
 cmd.ExecuteNonQuery()
 dc.Close()
 Membership.DeleteUser(User.Identity.Name)

 FormsAuthentication.SignOut()
 FormsAuthentication.RedirectToLoginPage()

But how do I deal with the table-name aspect of the statement when that is also the variable?

1 Answer 1

2

You can query information schema tables and then send your DROP queries based on that.

For example, this would list all tables that start with A:

SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'A%'

WHERE clause for DROP statement is not natively supported by SQL Server, because deleting a table is not something that happens often. You definitely don't want to do mass delete just like that in production.

Deleting a user account should require deleting records in one or many tables. You may want to consider redesign if you need to delete tables for that. A simple explanation, imagine 10000 accounts in an application, and 100 "tables" per account. Do you really want to have 1 million tables in your SQL database. How would you query against multiple users to produce reports for management? Things like that lead to common sense of having a record per user, +additional records for user detail, such as address, membership, permissions etc.

Sign up to request clarification or add additional context in comments.

3 Comments

I see. So I select all the tables first, then drop them. Sorry for my ignorance, how do I drop them after that? fill a dataset, then pull each name from the table, feeding the names into a drop command?
Yes, I tried everything to avoid the user created tables. For a number of reasons, it was beyond my ability to design (I could not make a table with a set number or columns, as the data varied on the users choices). Each user would only have 1 or 2 of these tables .
@Cory: You could fill a data set, yes. But since it's just one table, an easier option is to create a reader, then use DataTable.Load, as shown here, or use a data adapter to fill a table, as shown here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.