Reputation: 3678
I am trying to create a database table when the page loads. I tried this code :
System.Data.SqlClient.SqlConnection conn2 = new System.Data.SqlClient.SqlConnection(@"connectionstring");
string user2 = Page.User.Identity.Name + "imgs";
System.Data.SqlClient.SqlCommand ccmd = new System.Data.SqlClient.SqlCommand("CREATE TABLE '" + user2 + "' (id INT NOT NULL IDENTITY(1,1) PRIMARY KEY,img VARCHAR(225))", conn2);
conn2.Open();
ccmd.ExecuteNonQuery();
conn2.Close();
...but it doesn't work for me. What am I doing wrong?
Also - How can I check if a table exists in the database? I'm using asp.net 3.5
Upvotes: 0
Views: 328
Reputation: 2113
To check if a table exists in MSSQL, you can use this (example table name is 'users'):
IF EXISTS
( SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'users'
)
DROP TABLE users;
...or do whatever it is you want to do with the table afterwards, not just drop it obviously.
Upvotes: 2
Reputation: 12904
Change this;
CREATE TABLE '" + user2 + "'
(id INT NOT NULL IDENTITY(1,1)
PRIMARY KEY,img VARCHAR(225))
to
CREATE TABLE " + user2 + "
(id INT NOT NULL IDENTITY(1,1)
PRIMARY KEY,img VARCHAR(225))
Upvotes: 1