title: Sql Server Merge Statement in Python
body: <p>I am using sqlalchemy / pyodbc with MS SQL Server, and am trying to execute a raw SQL merge statement. If I take my query string and paste it into SQL Server Management Studio it works fine, but I can't seem to get it to work from Python. I've looked around a bit and can't seem to find questions on a similar issue. I realize this is quite possibly driven by issues specific to my setup but am hoping someone is able to help or at least point me in the right direction. Minimal example is below:</p>
  
  <pre><code>import sqlalchemy as sa
  engine = sa.create_engine('[your engine]')
  metadata = sa.MetaData(engine)
  
  t1 = sa.Table('test1', metadata, 
                sa.Column('id', sa.Integer, primary_key=True, autoincrement=False),
                sa.Column('name', sa.String(50)), schema='dbo')
  t2 = sa.Table('test2', metadata, 
                sa.Column('id', sa.Integer, primary_key=True, autoincrement=False),
                sa.Column('name', sa.String(50)), schema='dbo')
  t1.create()
  t2.create()
  
  query = "INSERT INTO dbo.test1 (id, name) VALUES (5, 'someguy')"
  engine.execute(query)
  mq = """MERGE dbo.test2 AS Target USING dbo.test1 AS Source ON
          Target.id = Source.id
          WHEN MATCHED THEN 
               UPDATE SET Target.name = Source.name
          WHEN NOT MATCHED BY TARGET THEN
               INSERT (id, name) VALUES (Source.id, Source.name);"""
  engine.execute(mq)
  </code></pre>