1

I have a T-SQL script to create a Database. I need to create this database runtime. When the application is Running.

What Connection String do I use?

How do I connect to the server and Create the Database? I am connecting to the server as a Network user. I am not using User "sa" I have a user "DBCreator"

My application is in C#.

I have this Script in T-SQL:

USE [master]
GO

CREATE DATABASE [XYZ]
-- Table Creation Code etc.

3 Answers 3

2

You can have two connection strings. One for master database to issue the CREATE DATABASE ... statement and another one for database created.

// You can use replace windows authentication with any user credentials who has proper permissions.
using (SqlConnection connection = new SqlConnection(@"server=(local);database=master;Integrated Security=SSPI"))
{
    connection.Open();

    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "CREATE DATABASE [XYZ]";
        command.ExecuteNonQuery();
    }
}

// Quering the XYZ database created
using (SqlConnection connection = new SqlConnection(@"server=(local);database=XYZ;Integrated Security=SSPI"))
{
    connection.Open();

    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "select * from sys.objects";
        ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the SMO objects to do that. I don't think i should explain what is already explained in details in a very good tutorial here

1 Comment

see the link i have posted.
1

Definitely use SMO its intended to do everything that SSMS can do, and more! it actually has a command called Database.Create(), follow this MSDN page

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.