Sqlserver
 SQL >> Datenbank >  >> RDS >> Sqlserver

Wie mache ich einen Upsert eines pandas DataFrame in eine Microsoft SQL Server Tabelle?

Es gibt zwei Möglichkeiten:

  1. Eine MERGE-Anweisung statt INSERT ... ON CONFLICT verwenden.
  2. Eine UPDATE-Anweisung mit JOIN verwenden, gefolgt von einem bedingten INSERT.

Die T-SQL-Dokumentation zu MERGE sagt:

Performance Tip: The conditional behavior described for the MERGE statement works best when the two tables have a complex mixture of matching characteristics. For example, inserting a row if it doesn't exist, or updating a row if it matches. When simply updating one table based on the rows of another table, improve the performance and scalability with basic INSERT, UPDATE, and DELETE statements.

In vielen Fällen ist es schneller und weniger kompliziert, einfach die getrennten UPDATE- und INSERT-Anweisungen zu verwenden.

engine = sa.create_engine(
    connection_uri,
    fast_executemany=True,
    isolation_level="SERIALIZABLE"
)

with engine.begin() as conn:
    # step 0.0 - create test environment
    conn.execute(sa.text("DROP TABLE IF EXISTS main_table"))
    conn.execute(
        sa.text("CREATE TABLE main_table (id int primary key, txt varchar(50))")
    )
    conn.execute(
        sa.text("INSERT INTO main_table (id, txt) VALUES (1, 'row 1 old text')")
    )

    # step 0.1 - create DataFrame to UPSERT
    df = pd.DataFrame(
        [(2, "new row 2 text"), (1, "row 1 new text")],
        columns=["id", "txt"]
    )

    # step 1 - upload DataFrame to temporary table
    df.to_sql("#temp_table", conn, index=False, if_exists="replace")

    # step 2 - merge temp_table into main_table
    conn.execute(
        sa.text("""
        UPDATE main
        SET main.txt = temp.txt
        FROM main_table main
        INNER JOIN #temp_table temp ON main.id = temp.id
        """)
    )
    conn.execute(
        sa.text("""
        INSERT INTO main_table (id, txt)
        SELECT id, txt FROM #temp_table
        WHERE id NOT IN (SELECT id FROM main_table)
        """)
    )

    # step 3 - confirm results
    result = conn.execute(sa.text("SELECT * FROM main_table ORDER BY id")).fetchall()
    print(result)
    # [(1, 'row 1 new text'), (2, 'new row 2 text')]