SQL script to create insert script

后端 未结 4 737
太阳男子
太阳男子 2021-02-05 15:39

A bit of a vague title, I will explain.

I am writing an SQL script to create an insert statement for each row of a table in my database, purely to be able to apply that

4条回答
  •  自闭症患者
    2021-02-05 16:12

    I wrote a python script based on @intgr answer to construct the select statement. It takes comma separated list of columns from stdin (use -).

    I wanted to use sqlparse but I couldn't understand how to use that lib.

    import fileinput
    
    names = ' '.join(fileinput.input())
    
    ns = [x.strip() for x in names.split(',')]
    quoted = ['quote_nullable(' + x + ')' for x in ns]
    insert = "SELECT  'INSERT INTO  ( " + (', ').join(ns) + " ) VALUES(' || " + (" || ',' || ").join(quoted)  + " || ');' FROM 
    " print insert

    A gist of the script is here: https://gist.github.com/2568047

    提交回复
    热议问题