1

I wrote a function that creates tables in MS SQL Server Express 2014. Here it is:

    private static void createAndAlterTables()
    {
        try
        {
            // Создать соединение с БД.
            using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConnection"].ConnectionString))
            {
                try
                {
                    SqlCommand sqlCom = new SqlCommand();
                    sqlCom.Connection = sqlCon;
                    sqlCon.Open();
                    MessageBox.Show("Выполняется создание таблиц", "Сообщение", MessageBoxButton.OK, MessageBoxImage.Information);
                    sqlCom.CommandText = @"CREATE TABLE [dbo].[AddedDevices](
                                          [Id] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
                                          [ProfileId] [uniqueidentifier] NULL,
                                          [MountingLocation] [nvarchar](max) NULL,
                                          [DeviceName] [nvarchar](50) NULL,
                                          [SerialNumber] [nvarchar](50) NULL,
                                          [DeviceDescription] [nvarchar](max) NULL,
                                          [OwnerCompany] [nvarchar](50) NULL,
                                          [StreetHouse] [nvarchar](max) NULL,
                                          [LocalityRegion] [nvarchar](max) NULL,
                                          [Country] [nvarchar](50) NULL,
                                          [ZipCode] [nvarchar](50) NULL,
                                          [SwHwVersion] [nvarchar](50) NULL,
                                          [DeviceType] [nvarchar](50) NULL,
                                          [SelectedInnerDiameter] [nvarchar](50) NULL,
                                          [SelectedBeamsQuantity] [nvarchar](50) NULL,
                                          [SelectedExClass] [nvarchar](50) NULL,
                                          [PathToStorageFolder] [nvarchar](max) NULL,
                                     CONSTRAINT [PK_AddedDevices] PRIMARY KEY CLUSTERED (
                                          [Id] ASC
                                       )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
                                     ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]";
                    sqlCom.ExecuteNonQuery();
                    MessageBox.Show("Таблица 'AddedDevices' успешно создана", "Сообщение", MessageBoxButton.OK, MessageBoxImage.Information);
                    //
                    sqlCom.CommandText = @"ALTER TABLE [dbo].[AddedDevices] ADD  CONSTRAINT [DF_AddedDevices_Id]  DEFAULT (newid()) FOR [Id]";
                    sqlCom.ExecuteNonQuery();
                    MessageBox.Show("Таблица 'AddedDevices' успешно изменена", "Сообщение", MessageBoxButton.OK, MessageBoxImage.Information);
                    //
                    sqlCom.CommandText = @"CREATE TABLE [dbo].[DeviceProfile](
                                          [Id] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
                                          [DeviceName] [nvarchar](100) NULL,
                                          [Brand] [nvarchar](50) NULL,
                                          [DisplayedName] [nvarchar](200) NULL,
                                          [RepositoryFileName] [nvarchar](200) NULL,
                                          [RegistersQuantity] [int] NULL,
                                          [DeviceTypeCode] [int] NULL,
                                          [SerialNumber] [nvarchar](100) NULL,
                                     CONSTRAINT [PK_DeviceProfile_Id] PRIMARY KEY CLUSTERED (
                                          [Id] ASC
                                       )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
                                     ) ON [PRIMARY]";
                    sqlCom.ExecuteNonQuery();
                    MessageBox.Show("Таблица 'DeviceProfile' успешно создана", "Сообщение", MessageBoxButton.OK, MessageBoxImage.Information);
                    //
                    sqlCom.CommandText = @"ALTER TABLE [dbo].[DeviceProfile] ADD  CONSTRAINT [DF_DeviceProfile_Id]  DEFAULT (newid()) FOR [Id]";
                    sqlCom.ExecuteNonQuery();
                    MessageBox.Show("Таблица 'DeviceProfile' успешно изменена", "Сообщение", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                        MessageBox.Show(ex.InnerException.Message, "Ошибка при создании таблиц", MessageBoxButton.OK, MessageBoxImage.Error);
                    else
                        MessageBox.Show(ex.Message, "Ошибка при создании таблиц", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        catch (Exception ex)
        {
            // Если сбой транзакции:
            if (ex.InnerException != null)
                MessageBox.Show(ex.InnerException.Message, "Ошибка при создании таблиц", MessageBoxButton.OK, MessageBoxImage.Error);
            else
                MessageBox.Show(ex.Message, "Ошибка при создании таблиц", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

When I connect to MS SQL Server Express 2014 and try to create table, then the result is successful. But when I connect to MS SQL Server Express LocalDB installed from prerequisite in InstallShield 2016 Premier (21 day trial), then tables are not created. Is there a reason in SQL Server type (Express and Express LocalDB)? Or I do anything wrong in my code. Your help will be highly appreciated.

Suraj Jain
  • 4,463
  • 28
  • 39
Prohor
  • 141
  • 1
  • 3
  • 12
  • 1
    The obvious answer is yes. Why are you asking? Do you get an error? An exception? Something? Post the *full* exception message, including the call stack. You can get that using `Exception.ToString` – Panagiotis Kanavos Jan 24 '17 at 11:09
  • 1
    And if there is no error, then how do you check the missing tables? Are you using DataDirectory in your connectionstring? – Steve Jan 24 '17 at 11:14
  • I do not use DataDirectory in my connectionstring. – Prohor Jan 24 '17 at 11:47
  • Panagiotis Kanavos, I ask because I must create tables in database on server but they are not created. Why? And I have no exceptions. – Prohor Jan 24 '17 at 11:48
  • This is the connection string: connectionString="Server=MY\SQLEXPRESS;Initial Catalog=My_Database;Integrated Security=SSPI" – Prohor Jan 24 '17 at 11:49
  • @Prohor that connection string is NOT a LocalDb one; this is a names sql express instance. How do you check that the tables are not there? – zaitsman Jan 24 '17 at 11:58
  • I bag you pardon I confused. This one is connection string: connectionString="Server=(LocalDB)\MSSQLLocalDB;Initial Catalog=My_Database;Integrated Security=SSPI" – Prohor Jan 24 '17 at 12:13
  • If you got no error, the tables have most probably been created. How, exactly, do you prove they haven't been created? Management Studio? Are you using the exact same instance name? Is there any code that forcibly recreates the database that you may have overlooked? – Jeroen Mostert Jan 25 '17 at 10:38

1 Answers1

0

Yes we can create table directly from C# an ADO.NET please check Some more example or things to remember when you create it from backend

Here is an simple example of creating a table that has an identity column:-

private void btnDatabase_Click(object sender, EventArgs e)
{
    using (SqlConnection connection =
    new SqlConnection("Data Source=(local);" +
              "Database='Exercise1';" +
              "Integrated Security=yes;"))
    {
    SqlCommand command =
        new SqlCommand("CREATE TABLE StoreItems( " +
               "StoreItemID int IDENTITY(1, 1) NOT NULL, " +
               "Category varchar(50), " +
               "[Item Name] varchar(100) NOT NULL, " +
               "Size varchar(20), " +
               "[Unit Price] money);",
               connection);
    connection.Open();
    command.ExecuteNonQuery();

    MessageBox.Show("A new table named StoreItems has been crated.");
    }
}
Community
  • 1
  • 1
Umang Patwa
  • 2,795
  • 3
  • 32
  • 41