自动更改 100+ 行长 SQL 脚本的第 N 个值以自动插入虚拟数据

Automatically change the Nth value of a 100+ line long SQL script for automatically inserting dummy data

我有一个很长的 SQL 脚本,我正在将其从 MySQL 语法转换为 Postgres。

大约有 100 多行用于插入虚拟数据的脚本,如下所示:

INSERT INTO product (sku, name, description, image_url, active, units_in_stock,
unit_price, category_id, date_created)
VALUES ('BOOK-TECH-1001', 'Spring Framework Tutorial', 'Learn Spring',
'assets/images/products/placeholder.png'
,1,100,29.99,1, NOW());

INSERT INTO product (sku, name, description, image_url, active, units_in_stock,
unit_price, category_id, date_created)
VALUES ('BOOK-TECH-1002', 'Kubernetes - Deploying Containers', 'Learn Kubernetes',
'assets/images/products/placeholder.png'
,1,100,24.99,1, NOW());

INSERT INTO product (sku, name, description, image_url, active, units_in_stock,
unit_price, category_id, date_created)
VALUES ('BOOK-TECH-1003', 'Internet of Things (IoT) - Getting Started', 'Learn IoT',
'assets/images/products/placeholder.png'
,1,100,29.99,1, NOW());

-- etc...

我想将插入的第 4 列的值更改为 true。在所有 100 多个插入语句中,它当前设置为 1,这在 MySQL 中将强制转换为该列中的布尔值,但在 Postgres 中不起作用。

我的问题是:是否有任何工具可以用来仅将每个语句第 4 列中 1 的值更改为 true

例如,我要更改以下内容:

INSERT INTO product (sku, name, description, image_url, active, units_in_stock,
unit_price, category_id, date_created)
VALUES ('BOOK-TECH-1001', 'Spring Framework Tutorial', 'Learn Spring',
'assets/images/products/placeholder.png'
,1,100,29.99,1, NOW());

对此:

INSERT INTO product (sku, name, description, image_url, active, units_in_stock,
unit_price, category_id, date_created)
VALUES ('BOOK-TECH-1001', 'Spring Framework Tutorial', 'Learn Spring',
'assets/images/products/placeholder.png'
,true,100,29.99,1, NOW());

有什么建议或我可以使用的在线工具吗? Ctrl + f 并将 1 替换为 true 将不起作用,因为我在插入语句中有另一个值,我想将其保留为 1.

有两种可能。

  • 您将值作为数字导入,然后执行并更新 set bool_col = true where numb_col = 1 然后删除 numb_col 并重命名 bool_col.
  • 您使用替换语句并替换
'
,1,

'
,true,

我特意包含了单引号和换行符的先例,以便我们只替换我们需要替换的 1 而不是任何其他的。

您可以在 INSERT 之前将数据类型更改为 integer,然后再更改为:

CREATE TABLE product (
   sku text NOT NULL,
   name text NOT NULL,
   description text,
   image_url text NOT NULL,
   active boolean NOT NULL,
   units_in_stock integer NOT NULL,
   unit_price numeric(15,2) NOT NULL,
   category_id integer NOT NULL,
   date_created timestamp with time zone NOT NULL
);

ALTER TABLE product ALTER active TYPE integer USING active::integer;

INSERT INTO product
   (sku, name, description,
    image_url, active, units_in_stock,
    unit_price, category_id, date_created)
VALUES ('BOOK-TECH-1001', 'Spring Framework Tutorial', 'Learn Spring',
        'assets/images/products/placeholder.png', 1, 100,
        29.99, 1, NOW());

ALTER TABLE product ALTER active TYPE boolean USING active::boolean;