postgresql 尝试创建一个插入函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5280637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to create an Insert function
提问by Adam
I'm trying to create a function in Postgres 8.4 using pgAdmin and I have the following code
我正在尝试使用 pgAdmin 在 Postgres 8.4 中创建一个函数,我有以下代码
CREATE OR REPLACE FUNCTION spcwriteperson(IN fname varchar(20))
RETURNS VOID AS
$BODY$
INSERT INTO person ("firstName") VALUES(fname);
$BODY$
LANGUAGE sql VOLATILE
COST 100;
when I try to run this, it complains that fname at VALUES(fname) is not a column. I'm coming from writing sprocs and functions in MySQL and Sql Server. Any help on why this doesn't work, or what I am doing wrong?
当我尝试运行它时,它抱怨 VALUES(fname) 处的 fname 不是列。我来自在 MySQL 和 Sql Server 中编写 sprocs 和函数。关于为什么这不起作用或我做错了什么的任何帮助?
回答by Jeremiah Peschka
If you don't like using numbered parameters, you can make use of PL/PGSQL:
如果您不喜欢使用编号参数,可以使用PL/PGSQL:
CREATE OR REPLACE FUNCTION spcwriteperson(fname varchar(20)) RETURNS VOID AS
$$
BEGIN
INSERT INTO person (firstName) VALUES (fname);
END
$$
LANGUAGE 'plpgsql';
PL/PGSQL will also give you a language more like SQL Server's T-SQL. PL/PGSQL has control structures, variables, and all of that fun stuff. PostgreSQL's SQL language implementation is much more strict about what functionality is available - it's a great implementation of SQL, but it's a querying language, not a procedural programming language.
PL/PGSQL 还将为您提供一种更像 SQL Server 的 T-SQL 的语言。PL/PGSQL 有控制结构、变量和所有有趣的东西。PostgreSQL 的 SQL 语言实现对于可用的功能要严格得多——它是 SQL 的一个很好的实现,但它是一种查询语言,而不是过程编程语言。
回答by Anomie
SQL-language functions' parameters are numbered, $1
, $2
, and so on. See the documentationfor details. You could use pgSQLif you want named parameters and more advanced capabilities.
SQL 语言函数的参数编号为 、$1
、$2
等。有关详细信息,请参阅文档。如果您想要命名参数和更高级的功能,您可以使用pgSQL。