将唯一记录从datatable导入到sql表

时间:2010-10-18 09:16:01

标签: c# sql ado.net datatable dataset

我有一个匹配MS Sql表结构的数据表,我想将数据表中的新记录导入SQL。

因此,在下面的示例中,我希望为Jim导入记录。

数据表:

Name   DOB        Country
Brian  11-11-78   USA
Dave   01-01-80   UK
Jim    02-02-81   FR

SQL:

Name   DOB        Country
Brian  11-11-78   USA
Dave   01-01-80   UK

3 个答案:

答案 0 :(得分:1)

您可以创建一个SP,并传递DataTable中的值,并使用MERGE (Transact-SQL)进行INSERT / UPDATE:

根据您的数据进行修剪,假设您的SQL表名称为_DOB

MERGE INTO _DOB AS Target

USING  (--SELECT NAME,DOB,COUNTRY FROM FROM YOUR DataTable
        VALUES ('Jim','1978-11-11', 'FR')
       )
       AS Source (Name, DOB, Country)
ON 
    Target.Name = Source.Name
    AND Target.DOB = Source.DOB

WHEN MATCHED THEN
    UPDATE SET 
        Target.Name = Source.Name,
        Target.DOB = Source.DOB,
        Target.Country = Source.Country

WHEN NOT MATCHED BY TARGET THEN
    INSERT (Name, DOB, Country) 
    VALUES (Source.Name, Source.DOB, Source.Country);

答案 1 :(得分:1)

这就是我最终的结果,似乎就是这个伎俩。感谢大家的投入。

this.conn = new oleDbConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);

OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM name", conn);

DataSet ds = new DataSet();

adapter.Fill(ds, "name");

DataTable data = ds.Tables["name"];

sqlCommand = "CREATE TABLE ##TempTable(Name, DOB, Location)";

SqlConnection SQLconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection1"].ConnectionString);
SQLconn.Open();

using (SqlCommand cmd = new SqlCommand(sqlCommand, SQLconn))
{
    cmd.CommandType = CommandType.Text;

    cmd.ExecuteReader();

    SqlBulkCopy bulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
    // Map the columns
    foreach (DataColumn col in data.Columns)
    bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
    bulkCopy.DestinationTableName = "##TempTable";
    bulkCopy.WriteToServer(data);
}

string MergeCommand = string.Concat("insert into [Existing Table] (Name, DOB, Location) ",
    "select distinct Name, DOB, Location from ##TempTable ",
    "WHERE NOT EXISTS (SELECT 1 FROM [Existing Table] a WHERE a.[Name] = ##TempTable.[Name] and a.[DOB] = ##TempTable.[DOB])");

SqlConnection Mergeconn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
Mergeconn.Open();

using (SqlCommand MergeCmd = new SqlCommand(MergeCommand, Mergeconn))
{
    MergeCmd.CommandType = CommandType.Text;
    MergeCmd.ExecuteReader();
}

SQLconn.Close();
Mergeconn.Close();

答案 2 :(得分:0)

INSERT INTO
    datatable (name, dob, country)
SELECT
    name, dob, country
FROM
    sql
WHERE
    NOT EXISTS(
        SELECT 
            *
        FROM
            datatable 
        WHERE
            datatable.name=sql.name AND
            datatable.dob=sql.dob
    )