【问题标题】:How to convert this into postgresql stored procedures in nodejs如何将其转换为nodejs中的postgresql存储过程
【发布时间】:2022-12-05 20:12:57
【问题描述】:

我想将 postgresql 查询更改为存储过程。

app.post("/add", async(req, res) => {
try {
    const { name, email, hobby } = req.body;
    const newStudent = await pool.query("INSERT INTO student (name, email, hobby) VALUES ($1, $2, $3) RETURNING *", [name, email, hobby]);
    res.json(newStudent.rows);
} catch (err) {
    console.error(err.message);
}

})

【问题讨论】:

  • 当您想要返回生成的值时,您需要一个函数。程序并不意味着返回某些东西。

标签: node.js postgresql stored-procedures stored-functions


【解决方案1】:
-- Create a stored procedure to insert a new student

CREATE OR REPLACE FUNCTION add_student (name VARCHAR, email VARCHAR, hobby VARCHAR)
RETURNS TABLE(id INT, name VARCHAR, email VARCHAR, hobby VARCHAR)
AS $$
BEGIN
    INSERT INTO student (name, email, hobby) VALUES (name, email, hobby) RETURNING *;
    RETURN QUERY SELECT * FROM student;
END;
$$ LANGUAGE plpgsql;
-- Execute the stored procedure to add a new student

SELECT add_student('John Doe', 'john@example.com', 'Gardening');

【讨论】:

  • 您的函数将在您每次调用它时返回整个表student 的内容。
  • @NeutroLink 您可以通过将代码放在仅包含三个反引号 (`) 的两行之间来格式化代码
猜你喜欢
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-10
  • 2020-10-12
  • 2020-09-28
  • 2013-10-10
  • 2021-07-14
相关资源
最近更新 更多