using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; namespace Create_DataTables { class Program { /**************************************** * to use this program first create a Database in * Sql Server called MitchellPaperCo. Add a table * called customer. It should have a definition of * * Create Table Customer( * CustomerID int identity(1,1) primary Key, * CustomerName varchar(50) * ) * * I populated it with 31 customers (thus the 1 to 31 in * the random statement for customerID) * Next create a table called Sales * * Create Table Sales( * SaleNumber int identity(1,1) primary key, * SaleDate Datetime, * SaleQuantity int, * CustomerID int foreignkey references Customer(CustomerID), * SaleTotal money * ) * * Once this table is created in sQl server you should be * able to run the code. When it runs the console screen will * pop up and will disappear when it is done. This can take as * as much as 30 minutes--possibly more depending on your * machine * Created by Steve Conger 7/29/2008 in VS 2008 * *******************************************/ static void Main(string[] args) { //create the database connection SqlConnection connect = new SqlConnection("Data Source=localhost;initial catalog=MitchellpaperCo;integrated security=true"); //create a new command object SqlCommand cmd = new SqlCommand(); //assign properties to the command object cmd.Connection = connect; //which connection to use // the SQL string with parameters cmd.CommandText = "Insert into Sales(SaleDate, SaleQuantity,CustomerID, SaleTotal) Values(@Date, @Quantity, @Cust, @tot)"; //create a paramaters collection to match the //sql statement and give them SQL data types cmd.Parameters.Add("@Date",SqlDbType.DateTime); cmd.Parameters.Add("@Quantity", SqlDbType.Int); cmd.Parameters.Add("@Cust",SqlDbType.Int); cmd.Parameters.Add("@tot",SqlDbType.Money); //open the connection connect.Open(); //loop a million times writing random values into the table for (int i = 1; i < 1000000; i++) { Random r = new Random(); int c = r.Next(1, 31); //customer number Random r2 = new Random(); int s = r2.Next(1, 100); //sale quantity Random r3 = new Random(); int d = r3.Next(1, 28); //day Random r4 = new Random(); int m = r4.Next(1, 12);//month string mydate = m.ToString() + @"/" + d.ToString() + @"/2008"; double tot = s * 5.95; //assign the random values to the parameters cmd.Parameters["@Date"].Value= DateTime.Parse(mydate); cmd.Parameters["@Quantity"].Value= s; cmd.Parameters["@Cust"].Value= c; cmd.Parameters["@tot"].Value= tot; cmd.ExecuteNonQuery();//run the insert query } //close the connection connect.Close(); } } }