我必须编写一个程序,它在Visual Studio 2010 C#和SQL Server 2012中的上述限制下将数据从表传输到表。 问题是找到一个高效的算法来做到这一点,因为表很长
private static void fillRows()
{
//i have
List<String> rows; // a list with table1 names (a,b,c,d,e...)
List<String> columnList; //list with table2 columnNames (a#mm,b#cm,c#m...)
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (var command = connection.CreateCommand())
{
}
}
}
答案 0 :(得分:0)
您可以旋转表格或结果集
答案 1 :(得分:0)
WITH NameValue AS (
SELECT [Name]
,CONVERT(float, StringValue) AS NumericValue
,Unit
FROM Table1
CROSS APPLY (
SELECT CHARINDEX(' ', [Value]) AS SpacePosition
) AS CA1
CROSS APPLY (
SELECT SUBSTRING([Value], 1, SpacePosition - 1) AS StringValue
,SUBSTRING([Value], SpacePosition + 1, LEN([Value]) - SpacePosition - 1) AS Unit
) AS CA2
)
,NumberedNameValue AS (
SELECT [Name]
,NumericValue
,Unit
,ROW_NUMBER() OVER (PARTITION BY [Name], Unit ORDER BY [Name]) AS RowNumber
FROM NameValue
)
INSERT INTO Table2 (
[ID], [a#mm], [b#cm], [c#m], [d#ml], [e#l], [f#dm],
)
SELECT RowNumber
,MAX(CASE WHEN [Name] = 'a' AND Unit = 'mm' THEN NumericValue ELSE 0 END)
,MAX(CASE WHEN [Name] = 'b' AND Unit = 'cm' THEN NumericValue ELSE 0 END)
,MAX(CASE WHEN [Name] = 'c' AND Unit = 'm' THEN NumericValue ELSE 0 END)
,MAX(CASE WHEN [Name] = 'd' AND Unit = 'ml' THEN NumericValue ELSE 0 END)
,MAX(CASE WHEN [Name] = 'e' AND Unit = 'l' THEN NumericValue ELSE 0 END)
,MAX(CASE WHEN [Name] = 'f' AND Unit = 'dm' THEN NumericValue ELSE 0 END)
FROM NumberedNameValue
GROUP BY RowNumber
答案 2 :(得分:0)
我不知道如何使用参数化查询来处理它,但它可以正常工作
private static void fillRows(List<String> columnList, String SOURCE_TABLE, String TARGET_TABLE, String COLUMN_NAME, String COLUMN_VALUE)
{
Console.WriteLine("Start filling");
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string selectSql = "SELECT " + COLUMN_NAME + "," + COLUMN_VALUE + " FROM " + SOURCE_TABLE;
SqlDataAdapter dataAdapter = new SqlDataAdapter(selectSql, connection);
DataTable dataTable = new DataTable("cache");
dataAdapter.Fill(dataTable);
//Set ID
int ID = 1;
string insertSql = "INSERT INTO " + TARGET_TABLE + " VALUES ('" + ID + "',";
StringBuilder sbInsertSQL = new StringBuilder();
sbInsertSQL.Append(insertSql);
int count = 0;
foreach (DataRow row in dataTable.Rows)
{
if (count == columnList.Count)
{
count = 0;
sbInsertSQL.Length--; //remove ','
sbInsertSQL.Append(");"); //complete command
SqlCommand sqlCmd = new SqlCommand(sbInsertSQL.ToString(), connection);
sqlCmd.ExecuteNonQuery(); //Insert row
//reset
sbInsertSQL.Clear();
ID++;
sbInsertSQL.Append("INSERT INTO " + TARGET_TABLE + " VALUES ('" + ID + "',");
}
//make sure, connecting correct
if (row[0].ToString().Equals(columnList[count].Split('#')[0])) //split off the unit
{
sbInsertSQL.Append("'" + tools.withoutUnit(row[1].ToString()) + "',");
count++;
}
}
connection.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
}
}