如何通过使用table1'"中的“执行”删除来获得结果?

时间:2014-11-11 13:12:02

标签: postgresql

当我使用execute命令运行sql cmd时,我想得到它的结果。 我们知道,当我使用时,我可以通过变量sc获得总计数:

execute 'select * from table" into sc;

但是如何使用以下方法获得结果:

execute 'delete from table1'"? 

当我使用INTO时,结果是

ERROR: "INTO used with a command that cannot return data"

2 个答案:

答案 0 :(得分:1)

execute 'WITH row_deleted AS (DELETE FROM table1 RETURNING *) SELECT count(*) FROM row_deleted' into c; 

您可以在pl sql函数中使用它,如下所示:

--Drop the table and the functin if it exist:
DROP TABLE IF EXISTS table1;

DROP FUNCTION if exists _deleted_rows();
--Create the table for the example:
CREATE TABLE table1
(
  row_id serial NOT NULL,
  col1 character varying,
  CONSTRAINT table1_pkey PRIMARY KEY (row_id)
);

--Insert some rows:
insert into table1 (col1) values ('test1');
insert into table1 (col1) values ('test2');
insert into table1 (col1) values ('test3');

--Ctreate the function that count the number of deleted rows of the table: table1
CREATE OR REPLACE FUNCTION _deleted_rows()
  RETURNS character varying AS
$BODY$declare 
nbr_deleted  integer;
begin
    execute 'WITH row_deleted AS (DELETE FROM table1 RETURNING *) SELECT count(*) FROM row_deleted' into nbr_deleted;
    return (nbr_deleted);
end;$BODY$
LANGUAGE plpgsql VOLATILE;

测试该函数(在sql小提琴上出现问题构建模式):

select * from _deleted_rows();

 _deleted_rows
---------------
 3
(1 ligne)

Execute命令

DELETE命令

答案 1 :(得分:0)

我有点不清楚你要做什么,但你应该能够使用"返回"。在这里,我只是返回已删除的行:

CREATE TEMP TABLE foo(id int, description text);
INSERT INTO foo VALUES
(1, 'HELLO'),
(2, 'WORLD');

DELETE FROM foo returning *;
+----+-------------+
| id | description |
+----+-------------+
|  1 | HELLO       |
|  2 | WORLD       |
+----+-------------+
(2 rows)

另外,如果你需要他们移动"进入"一个表(例如),您可以执行以下操作:

DROP TABLE IF EXISTS foo;
DROP TABLE IF EXISTS deleted_foo;

CREATE TEMP TABLE foo(id int, description text);
INSERT INTO foo VALUES
(1, 'HELLO'),
(2, 'WORLD');

CREATE TEMP TABLE deleted_foo(id int, description text);

WITH x AS (DELETE FROM foo RETURNING *)
INSERT INTO deleted_foo
SELECT * FROM x;

SELECT * FROM deleted_foo;

+----+-------------+
| id | description |
+----+-------------+
|  1 | HELLO       |
|  2 | WORLD       |
+----+-------------+
(2 rows)

假设您是从plpgsql函数中执行此操作,您还可以使用ROW_COUNT变量。例如:

GET DIAGNOSTICS integer_var = ROW_COUNT;

这将为您提供已删除的行数。