SQL script to create insert script

后端 未结 4 693
太阳男子
太阳男子 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:13

    Use the quote_nullable() function new in PostgreSQL 8.4. In addition to permitting NULL values, it retains your data types and protects you from Bobby Tables (SQL injections):

    SELECT 'INSERT INTO products (id,name,description) VALUES (' ||
    quote_nullable(ID) || ',' || quote_nullable(name) || ',' ||
    quote_nullable(description) || ');' FROM products;
    

    In older versions, you get the same behavior with coalesce() and quote_literal():

    SELECT 'INSERT INTO products (id,name,description) VALUES (' ||
    coalesce(quote_literal(ID), 'null') || ',' ||
    coalesce(quote_literal(name), 'null') || ',' ||
    coalesce(quote_literal(description), 'null') || ',' ||
    ');' FROM products;
    

提交回复
热议问题