Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# SQL create table IF it doesn't already exist [duplicate]

Tags:

c#

sql

Hey, I am trying to put a little logic into my C# app that will create a table called Import, IF it doesn't already exist.. here is my code, it doesn't seem to work tho.

con.Open();
                    using (SqlCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandText =
                            @" 
                       IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'RX_CMMData' AND TABLE_NAME = 'Import'))
BEGIN
CREATE TABLE Import (
  RowId     integer PRIMARY KEY NOT NULL,
  PartNumber  varchar(200) NOT NULL,
  CMMNumber   varchar(200) NOT NULL,
  Date        varchar(200) NOT NULL,
  FeatType    varchar(200) NOT NULL,
  FeatName    varchar(200) NOT NULL,
  Value       varchar(200) NOT NULL,
  Actual      decimal,
  Nominal     decimal,
  Dev         decimal,
  TolMin      decimal,
  TolPlus     decimal,
  OutOfTol    decimal,
  FileName    varchar(200) NOT NULL
); END";
                        cmd.ExecuteNonQuery();
                    }
                    con.Close();
like image 402
Jake Sankey Avatar asked Nov 23 '25 09:11

Jake Sankey


1 Answers

Your SQL is creating the table if it does exist and not if it doesn't.

Change the SQL to read IF NOT EXISTS.

like image 106
Marc Tidd Avatar answered Nov 24 '25 22:11

Marc Tidd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!