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?

Cory
  • 1,263
  • 16
  • 31

1 Answers1

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.

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
  • 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? – Cory Aug 12 '14 at 20:41
  • 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 Aug 12 '14 at 20:49
  • @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](http://msdn.microsoft.com/en-us/library/7x8ccbsb%28v=vs.100%29.aspx), as shown [here](http://stackoverflow.com/a/13870892/897326), or use a data adapter to fill a table, as shown [here](http://stackoverflow.com/a/13870900/897326). – Victor Zakharov Aug 12 '14 at 21:50