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.
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.");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.