postgresql 将数据库值转换为Postgres中的变量

gtlvzcf8  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(137)

我对Postgres开发非常陌生,想写一个函数(spUserTest)来查找一个值,然后使用该值从表中提取数据。
我的代码运行如下:

表定义

-- auto-generated definition
create table "user"
(
    userid         uuid not null
        constraint pk__user__1788ccac19748a10
            primary key
        constraint uq__user__1788ccad4f14aa65
            unique,
    username       varchar(100)
        constraint uq__user__c9f2845657920267
            unique,
    passwordhash   bytea,
    firstname      varchar(40),
    lastname       varchar(40),
    salt           uuid,
    organisationid uuid
        constraint fk_user_organisation_organisationid
            references organisation,
    sessiontoken   uuid,
    sessionage     timestamp with time zone
);

alter table "user"
    owner to postgres;

-- auto-generated definition
create table userdevice
(
    userdeviceid uuid not null
        constraint pk__userdevi__fd151c39ccac5a1d
            primary key,
    userid       uuid
        constraint fkuser_userdevice_userid
            references "user",
    deviceid     uuid
        constraint fkuser_userdevice_deviceid
            references device,
    constraint unique_userid_deviceid
        unique (userid, deviceid)
);

alter table userdevice
    owner to postgres;

字符串

spUserTest函数

create function spuserTest(username2 text)
    returns TABLE(UserDeviceID uuid, UserID uuid, DeviceID uuid)
    language sql
as
 do $$

  declare
       UserID2     uuid;

begin

    UserID2 := (SELECT t.userid from dbo.user t where t.username = username2);

RETURN QUERY
        SELECT
            UserDeviceID ::text,
            UserID  ::text,
            DeviceID ::text
        FROM
            dbo.userdevice
        where
            UserID = UserID2;

END $$;


所以在函数spUserTest中,我想做以下事情:
1.使用username2从User表中查找Userid
1.然后使用userID的值从表UserDevice中提取数据
但是当我运行这个时,我得到以下错误:

[2023-10-31 12:18:38] [42601] ERROR: syntax error at end of input
[2023-10-31 12:18:38] Position: 131


我做错什么了?

cu6pst1q

cu6pst1q1#

在PL/pgSQL中,你(通常)不把SELECT的结果赋给变量-你使用SELECT.. INTO语句。
所以,

UserID2 := (SELECT t.userid from dbo.user t where t.username = username2);

字符串

SELECT t.userid
  INTO UserID2
  from dbo.user t
  where t.username = username2;


另一种选择是完全消除UserID2的单独获取,并将dbo.user查询嵌入到主查询中:

SELECT  
        UserDeviceID ::text,
        UserID  ::text,
        DeviceID ::text
    FROM
        dbo.userdevice
    where
        UserID IN (SELECT userid
                     from dbo.user
                     where username = username2)

相关问题