Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a SQL Server table from a C# datatable

I have a DataTable that I manually created and loaded with data using C#.

What would be the most efficient way to create a table in SQL Server 2005 that uses the columns and data in the DataTable?

like image 829
alchemical Avatar asked Aug 28 '09 18:08

alchemical


People also ask

Can you use SQL with C?

You can code SQL statements in a C or C++ program wherever you can use executable statements. Each SQL statement in a C or C++ program must begin with EXEC SQL and end with a semicolon (;). The EXEC and SQL keywords must appear on one line, but the remainder of the statement can appear on subsequent lines.

Can we connect C to database?

You can then add a new C source file and replace it with this content. Using the ODBC APIs SQLAllocHandle, SQLSetConnectAttr, and SQLDriverConnect, you should be able to initialize and establish a connection to your database.


1 Answers

public static string CreateTABLE(string tableName, DataTable table) {     string sqlsc;     sqlsc = "CREATE TABLE " + tableName + "(";     for (int i = 0; i < table.Columns.Count; i++)     {         sqlsc += "\n [" + table.Columns[i].ColumnName + "] ";         string columnType = table.Columns[i].DataType.ToString();         switch (columnType)         {             case "System.Int32":                 sqlsc += " int ";                 break;             case "System.Int64":                 sqlsc += " bigint ";                 break;             case "System.Int16":                 sqlsc += " smallint";                 break;             case "System.Byte":                 sqlsc += " tinyint";                 break;             case "System.Decimal":                 sqlsc += " decimal ";                 break;             case "System.DateTime":                 sqlsc += " datetime ";                 break;             case "System.String":             default:                 sqlsc += string.Format(" nvarchar({0}) ", table.Columns[i].MaxLength == -1 ? "max" : table.Columns[i].MaxLength.ToString());                 break;         }         if (table.Columns[i].AutoIncrement)             sqlsc += " IDENTITY(" + table.Columns[i].AutoIncrementSeed.ToString() + "," + table.Columns[i].AutoIncrementStep.ToString() + ") ";         if (!table.Columns[i].AllowDBNull)             sqlsc += " NOT NULL ";         sqlsc += ",";     }     return sqlsc.Substring(0,sqlsc.Length-1) + "\n)"; } 
like image 151
Amin Avatar answered Oct 05 '22 03:10

Amin