Reputation: 1283
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?
Upvotes: 1
Views: 464
Reputation: 26454
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.
Upvotes: 2