In this example, we’ll learn how to create a table in Sql Server Database by using C# because programmers often need to create tables programmatically.
To create the database, follow these steps:
- Create a new Visual C# .NET Console Application.
- Use the using statement on the System and System.Data namespaces so that you do not have to qualify declarations in those namespaces later in your code. Add the following code to the General Declarations. 123using System.Data.SqlClient;
3. Add the following sample code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | static void Main(string[] args) { SqlConnection con; SqlCommand cmd; /*creating or openning database*/ con = new SqlConnection("server=.; Initial Catalog = MyDatabase; Integrated Security = SSPI"); string sql = @"IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='Student' AND xtype='U') CREATE TABLE [dbo].[Student]( [id] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY, [FirstName] [nchar](10) NULL, [LastName] [nchar](10) NULL, )"; con.Open(); cmd = new SqlCommand(sql, con); cmd.ExecuteNonQuery(); con.Close(); Console.ReadKey(); } |
4. Press F5 or CTRL+F5 to run the project, and Create Table in Sql Server Database.