source

SQL Server 데이터베이스 테이블에 데이터 테이블을 삽입하는 방법은 무엇입니까?

ittop 2023. 7. 16. 17:56
반응형

SQL Server 데이터베이스 테이블에 데이터 테이블을 삽입하는 방법은 무엇입니까?

했습니다.datatable 이 를 제 이제이내컴저다니장합에 SQL Server데이터베이스

웹에서 많은 정보를 보았지만 이해할 수 없습니다.

  1. 누군가가 한 줄씩 추가로 대량 업데이트를 제안한다고 말했습니다.etc: 무엇이 더 좋습니까?
  2. 을 사용해야 ?OLE또는SQL Server:dataAdapter또는connection)?

제가 필요로 하는 것은 직원의 엑셀 파일에서 주간 업무 보고서를 읽고 모든 보고서가 저장되는 데이터베이스 테이블에 저장하는 것입니다(데이터베이스를 매주 새 레코드로 업데이트).

Excel 파일에는 현재 주에 대한 보고서만 포함되어 있습니다.

성을 합니다.User-Defined TableType데이터베이스:

CREATE TYPE [dbo].[MyTableType] AS TABLE(
    [Id] int NOT NULL,
    [Name] [nvarchar](128) NULL
)

하여 매개변수를 합니다.Stored Procedure:

CREATE PROCEDURE [dbo].[InsertTable]
    @myTableType MyTableType readonly
AS
BEGIN
    insert into [dbo].Records select * from @myTableType 
END

그리고 당신의 것을 보냅니다.DataTableserver:sql server 파일에 :

using (var command = new SqlCommand("InsertTable") {CommandType = CommandType.StoredProcedure})
{
    var dt = new DataTable(); //create your own data table
    command.Parameters.Add(new SqlParameter("@myTableType", dt));
    SqlHelper.Exec(command);
}

저장 프로시저 내부의 값을 편집하려면 동일한 유형의 로컬 변수를 선언하고 입력 테이블을 삽입할 수 있습니다.

DECLARE @modifiableTableType MyTableType 
INSERT INTO @modifiableTableType SELECT * FROM @myTableType

그러면 편집할 수 있습니다.@modifiableTableType:

UPDATE @modifiableTableType SET [Name] = 'new value'

데이터 테이블을 처음으로 저장하는 경우

대량 복사를 사용하여 이 작업을 수행합니다.PK/FK 제약 조건이 없는지 확인합니다.

SqlBulkCopy bulkcopy = new SqlBulkCopy(myConnection);
//I assume you have created the table previously
//Someone else here already showed how  
bulkcopy.DestinationTableName = table.TableName;
try                             
{                                 
    bulkcopy.WriteToServer(table);                            
}     
    catch(Exception e)
{
    messagebox.show(e.message);
} 

이미 기본 기록을 가지고 계시기 때문에.그리고 당신은 기존의 기록으로 새로운 기록을 확인하고 싶을 뿐입니다.간단하게 할 수 있습니다.

기본적으로 데이터베이스에서 기존 테이블을 가져옵니다.

DataTable Table = new DataTable();

SqlConnection Connection = new SqlConnection("ConnectionString");
//I assume you know better what is your connection string

SqlDataAdapter adapter = new SqlDataAdapter("Select * from " + TableName, Connection);

adapter.Fill(Table);

그런 다음 이 테이블을 이 함수로 전달합니다.

public DataTable CompareDataTables(DataTable first, DataTable second)
{
    first.TableName = "FirstTable";
    second.TableName = "SecondTable";

    DataTable table = new DataTable("Difference");

    try
    {
        using (DataSet ds = new DataSet())
        {
            ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });

            DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];

            for (int i = 0; i < firstcolumns.Length; i++)
            {
                firstcolumns[i] = ds.Tables[0].Columns[i];
            }

            DataColumn[] secondcolumns = new DataColumn[ds.Table[1].Columns.Count];

            for (int i = 0; i < secondcolumns.Length; i++)
            {
                secondcolumns[i] = ds.Tables[1].Columns[i];
            }

            DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);

            ds.Relations.Add(r);

            for (int i = 0; i < first.Columns.Count; i++)
            {
                table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);
            }

            table.BeginLoadData();

            foreach (DataRow parentrow in ds.Tables[0].Rows)
            {
                DataRow[] childrows = parentrow.GetChildRows(r);
                if (childrows == null || childrows.Length == 0)
                    table.LoadDataRow(parentrow.ItemArray, true);
            }

            table.EndLoadData();

        }
    }

    catch (Exception ex)
    {
        throw ex;
    }

    return table;
}

이렇게 하면 변경된 행이 업데이트된 새 데이터 테이블이 반환됩니다.함수를 올바르게 호출했는지 확인하십시오.데이터 테이블이 먼저 최신 상태가 되어야 합니다.

그런 다음 이 새 데이터 테이블을 사용하여 대량 복사 기능을 처음부터 다시 반복합니다.

솔루션에 사용한 매우 간단한 코드를 제공합니다(당신의 문제 설명과 동일한 문제 설명을 가지고 있습니다).

    SqlConnection con = connection string ;
//new SqlConnection("Data Source=.;uid=sa;pwd=sa123;database=Example1");
con.Open();
string sql = "Create Table abcd (";
foreach (DataColumn column in dt.Columns)
{
    sql += "[" + column.ColumnName + "] " + "nvarchar(50)" + ",";
}
sql = sql.TrimEnd(new char[] { ',' }) + ")";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
using (var adapter = new SqlDataAdapter("SELECT * FROM abcd", con)) 
using(var builder = new SqlCommandBuilder(adapter))
{
adapter.InsertCommand = builder.GetInsertCommand();
adapter.Update(dt);
// adapter.Update(ds.Tables[0]); (Incase u have a data-set)
}
con.Close();

미리 정의된 테이블 이름을 "abcd"로 지정했습니다(이 이름의 테이블이 데이터베이스에 존재하지 않도록 주의해야 합니다).제 대답이 당신에게 효과가 있다면 투표해주세요!!!!:)

이 기사에서 제안한 대로 대량 삽입을 추천합니다: C# DataTableSQL server OpenXML 기능을 사용한 대량 데이터 삽입

public bool BulkCopy(ExcelToSqlBo objExcelToSqlBo, DataTable dt, SqlConnection conn, SqlTransaction tx)
{
    int check = 0;
    bool result = false;
    string getInsert = "";
    try
    {
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow dr in dt.Rows)
            {
                if (dr != null)
                {
                    if (check == 0)
                    {
                        getInsert = "INSERT INTO [tblTemp]([firstName],[lastName],[Father],[Mother],[Category]" +
                                ",[sub_1],[sub_LG2])"+
                                " select '" + dr[0].ToString() + "','" + dr[1].ToString() + "','" + dr[2].ToString() + "','" + dr[3].ToString() + "','" + dr[4].ToString().Trim() + "','" + dr[5].ToString().Trim() + "','" + dr[6].ToString();

                        check += 1;
                    }
                    else
                    {
                        getInsert += " UNION ALL ";

                        getInsert += " select  '" + dr[0].ToString() + "','" + dr[1].ToString() + "','" + dr[2].ToString() + "','" + dr[3].ToString() + "','" + dr[4].ToString().Trim() + "','" + dr[5].ToString().Trim() + "','" + dr[6].ToString() ;

                        check++;
                    }
                }
            }
            result = common.ExecuteNonQuery(getInsert, DatabasesName, conn, tx);
        }
        else
        {
            throw new Exception("No row for insertion");
        }
        dt.Dispose();
    }
    catch (Exception ex)
    {
        dt.Dispose();
        throw new Exception("Please attach file in Proper format.");
    }
    return result;
} 
    //best way to deal with this is sqlbulkcopy 
    //but if you dont like it you can do it like this
    //read current sql table in an adapter
    //add rows of datatable , I have mentioned a simple way of it
    //and finally updating changes

    Dim cnn As New SqlConnection("connection string")        
    cnn.Open()
    Dim cmd As New SqlCommand("select * from  sql_server_table", cnn)
    Dim da As New SqlDataAdapter(cmd)       
    Dim ds As New DataSet()
    da.Fill(ds, "sql_server_table")
    Dim cb As New SqlCommandBuilder(da)        

    //for each datatable row
    ds.Tables("sql_server_table").Rows.Add(COl1, COl2)

    da.Update(ds, "sql_server_table")

테이블에 기본 키가 있으면 테이블 행을 한 행씩 추가하는 것이 더 낫다는 것을 알게 되었습니다.전체 테이블을 한 번에 삽입하면 자동 증분에서 충돌이 발생합니다.

저장된 프로세스입니다.

CREATE PROCEDURE dbo.usp_InsertRowsIntoTable
@Year       int,
@TeamName   nvarchar(50),
AS
INSERT INTO [dbo.TeamOverview]
(Year,TeamName)
VALUES (@Year, @TeamName);
RETURN

테이블에 추가해야 하는 모든 행에 대해 이 코드를 반복합니다.

insertRowbyRowIntoTable(Convert.ToInt16(ddlChooseYear.SelectedValue), name);

데이터 액세스 계층 코드는 다음과 같습니다.

        public void insertRowbyRowIntoTable(int ddlValue, string name)
    { 
        SqlConnection cnTemp = null;
        string spName = null;
        SqlCommand sqlCmdInsert = null;

        try
        {
            cnTemp = helper.GetConnection();
            using (SqlConnection connection = cnTemp)
            {
                if (cnTemp.State != ConnectionState.Open)
                    cnTemp.Open();
                using (sqlCmdInsert = new SqlCommand(spName, cnTemp))
                {
                    spName = "dbo.usp_InsertRowsIntoOverview";
                    sqlCmdInsert = new SqlCommand(spName, cnTemp);
                    sqlCmdInsert.CommandType = CommandType.StoredProcedure;

                    sqlCmdInsert.Parameters.AddWithValue("@Year", ddlValue);
                    sqlCmdInsert.Parameters.AddWithValue("@TeamName", name);

                    sqlCmdInsert.ExecuteNonQuery();

                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (sqlCmdInsert != null)
                sqlCmdInsert.Dispose();

            if (cnTemp.State == ConnectionState.Open)
                cnTemp.Close();
        }

    }

제가 그 질문에 대해 이해한 바로는, 이것은 꽤 간단한 해결책을 사용할 수 있습니다.아래의 방법이 제가 제안하는 방법입니다. 이 방법은 데이터 테이블을 가져온 다음 SQL 문을 사용하여 데이터베이스의 테이블에 삽입합니다.내 솔루션은 MySQL Connection을 사용하고 있으며 MySqlCommand는 이를 SqlConnection 및 SqlCommand로 대체합니다.

public void InsertTableIntoDB_CreditLimitSimple(System.Data.DataTable tblFormat)
    {
        for (int i = 0; i < tblFormat.Rows.Count; i++)
        {

            String InsertQuery = string.Empty;

            InsertQuery = "INSERT INTO customercredit " +
                          "(ACCOUNT_CODE,NAME,CURRENCY,CREDIT_LIMIT) " +
                          "VALUES ('" + tblFormat.Rows[i]["AccountCode"].ToString() + "','" + tblFormat.Rows[i]["Name"].ToString() + "','" + tblFormat.Rows[i]["Currency"].ToString() + "','" + tblFormat.Rows[i]["CreditLimit"].ToString() + "')";



            using (MySqlConnection destinationConnection = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
            using (var dbcm = new MySqlCommand(InsertQuery, destinationConnection))
            {
                destinationConnection.Open();
                dbcm.ExecuteNonQuery();
            }
        }
    }//CreditLimit

언급URL : https://stackoverflow.com/questions/9075159/how-to-insert-a-data-table-into-sql-server-database-table

반응형