Click here to Skip to main content
15,902,299 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm working on a c# project and now I need to create a table in sql,but I just need to create it if it doesnt exist.

What I have tried:

I did a search on google and found this, but for some reason isnt working, this ignores the
if
and just creates the table and if the table already exist it skips all my code, but I get no error
C#
conn.Open();
SqlCommand command = new SqlCommand("IF OBJECT_ID('UXMenu', 'U') IS NULL CREATE TABLE UXMenu(TransDocument char(10), TransSerial char(8), TransDocNumber float, PartyName char(75), PartyLocalityID char(5), TotalAmount char (25), ShipToPostalCode char(50), Estado int);", conn);
command.ExecuteNonQuery();
MessageBox.Show("tabela criada");
conn.Close();
Posted
Updated 24-Aug-17 4:14am
v2

1 solution

Um. You did notice that your command checks for one table, and if it doesn't exist creates a table with a totally different name?
SQL
IF OBJECT_ID('UXFaturas', 'U') IS NULL CREATE TABLE UXMenu(...);


And if it is corrected, then if it finds the table or not there is nothing to error. You could add an error if it does exist:
SQL
IF OBJECT_ID('UXMenu', 'U') IS NULL 
   CREATE TABLE UXMenu(TransDocument char(10), TransSerial char(8), TransDocNumber float, PartyName char(75), PartyLocalityID char(5), TotalAmount char (25), ShipToPostalCode char(50), Estado int);
ELSE 
   THROW 50001, 'Table Exists', 1;
 
Share this answer
 
Comments
Member 13356973 24-Aug-17 9:59am    
I changed the table name and forgot to change that, thanks for the help
Member 13356973 24-Aug-17 10:09am    
It still skips my code if the table exists
OriginalGriff 24-Aug-17 10:26am    
How have you checked?
Member 13356973 24-Aug-17 10:27am    
I run the program and added a messagebox when it goes for the create table, but i've fixed it, thanks for the help
OriginalGriff 24-Aug-17 10:34am    
Don't use MessageBox to follow what your code is doing - use the debugger, it gives you a huge amount more help and control.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900