R
R
rundll322022-03-20 17:45:32
SQL
rundll32, 2022-03-20 17:45:32

Sql CreateTable runs indefinitely?

I created a local database through the Context menu - Add - a database based on services,
I wrote a small class where I copied the connection string from the object:

public static class Database
    {
        public static SqlConnection Connection { set; get; }

        public static void CreateConnection()
        {
            var connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Data\MyDb.mdf;Integrated Security=True";
            Connection = new SqlConnection(connectionString);
        }
}


Then the fun begins, I need to create a table with certain fields, as a result I came to this code:
public static void CreateTable(string fileName, string[] fields)
        {
            var tableFields = string.Join(Environment.NewLine, fields.Select(x => $"[{x}] NVARCHAR(250) NULL,"));
            var sql = [email protected]"CREATE TABLE [dbo].[{fileName}] (
    [Id]  INT IDENTITY (1, 1) NOT NULL,
    {tableFields}
    PRIMARY KEY CLUSTERED ([Id] ASC)
);";

            Connection.Open();
            var com = new SqlCommand(sql, Connection);
            int result = com.ExecuteNonQuery();
            Connection.Close();
        }


But nothing happens, I have already tried both DataTable and a bunch of code from StackOverflow, but I don’t even have exceptions, it’s just that nothing happens further than com.ExecuteNonQuery.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2022-03-25
@rundll32

Check in the studio - the table was created or not?
If not, then get the script in the debugger and run it in the studio. An error may occur during creation...
And before creating a table, you actually need to check its existence...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question