【问题标题】:can't use string in function at postgresql [duplicate]不能在postgresql的函数中使用字符串[重复]
【发布时间】:2018-10-16 16:12:54
【问题描述】:

我对 postgresql 函数有一些问题。 我的表名是 people,name 是 text,year 是 integer。

我喜欢写这样的函数:

create function add() returns void as '
insert into people(name, year) VALUES ('danilo', 12)

' LANGUAGE SQL;

我无法插入字符串,例如 danilo。

错误:“danilo”处或附近的语法错误

我试过了

...
insert into people(name, year) VALUES ( \'danilo\', 12)
...

但不起作用。

这很好用:

...insert into people( year) VALUES ( 12)...

还有这个:

create function add(text) returns void as '
insert into people(name, year) VALUES ($1, 12)

' LANGUAGE SQL;

select add('danilo');

但我该怎么做:

...
insert into people(name, year) VALUES ('danilo', 12)
...

谁能帮帮我?

谢谢。

【问题讨论】:

标签: postgresql


【解决方案1】:

您的案例就是很好的例子,为什么 PostgreSQL 有自定义字符串分隔符 - 符号 $some$。自定义字符串分隔符应成对使用。

postgres=# select $_$Hello$_$;
 ?column? 
----------
 Hello
(1 row)

撇号没有问题

postgres=# select $_$He'llo$_$;
 ?column? 
----------
 He'llo
(1 row)

所以你的代码应该看起来像

create function add(text)
returns void as $$
insert into people(name, year) VALUES ('Hello', 12)
$$ LANGUAGE SQL;

【讨论】:

    【解决方案2】:

    我有答案:

    使用''danilo'',加倍'

    转义单引号 ' 通过将它们加倍 ''

    create function add() returns void as '
    insert into people(name, year) VALUES (''danilo'', 12)
    
    ' LANGUAGE SQL;
    

    【讨论】:

      【解决方案3】:

      你必须用双单引号转义

      create function add() returns void as '
      insert into people(name, year) VALUES (''danilo'', 12)
      ' LANGUAGE SQL;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-15
        • 2021-01-05
        相关资源
        最近更新 更多