简体   繁体   English

使用 postgresql function 声明并返回一个 json 变量

[英]Declare and return a json variable with postgresql function

I'm trying to create a function PostgreSQL to check if a user exist in a table users by creating a function who return a JSON variable.我正在尝试创建一个 function PostgreSQL 通过创建一个返回 JSON 变量的 function 来检查表用户中是否存在用户。

CREATE OR REPLACE FUNCTION login( uname character varying(55),pswd character varying(55)) 
RETURNS json AS
$$
DECLARE
  msg json ;
BEGIN
IF ((SELECT COUNT(*) FROM (SELECT * FROM users WHERE username=uname and password=pswd) AS row_count) =1)
THEN
msg="{ 'stat' : 'active' }";
    RETURN msg;
ELSE
msg="{ 'stat' : 'inactive' }";
    RETURN msg;
END IF;    
END;
$$ LANGUAGE plpgsql;

But when I try to using it it's return me the following error: ERROR: column "{ 'stat': 'inactive' }" does not exist但是当我尝试使用它时,它返回以下错误:错误:列“{'stat':'inactive'}”不存在

String constants need to be enclosed in single quotes in SQL (and PL/pgSQL).在 SQL(和 PL/pgSQL)中,字符串常量需要用单引号括起来。 And JSON uses double quotes for keys and values, so { 'stat': 'active' } is invalid JSON as well.而 JSON 对键和值使用双引号,因此{ 'stat': 'active' }也是无效的 JSON。

You need:你需要:

msg := '{"stat": "active"}';

The variable isn't really needed, you could also use:该变量并不是真正需要的,您也可以使用:

return '{"stat": "active"}';

Note that the IF condition can be made a bit more efficient by using an EXISTS condition:请注意,使用 EXISTS 条件可以使 IF 条件更有效:

if exists (SELECT * FROM users WHERE username=uname and password=pswd) 
then 
  ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM