📜  PostgreSQL – 行类型变量

📅  最后修改于: 2022-05-13 01:57:06.214000             🧑  作者: Mango

PostgreSQL – 行类型变量

PostgreSQL 使用Row 类型变量来存储select into语句返回的结果集的整行。

宣言 :

我们可以使用以下语法声明一个与表行或视图中的相应数据类型具有相同数据类型的行类型变量:

Syntax :
row_variable table_name/view_name %ROWTYPE;

我们可以使用点符号 (.) 来访问行变量中的任何字段。

Syntax :
row_variable.field_name

首先,我们使用以下命令创建一个示例表来执行示例:

CREATE TABLE employees (
 employee_id serial PRIMARY KEY,
 full_name VARCHAR NOT NULL,
 manager_id INT
);

然后我们将数据插入到我们的员工表中,如下所示:

INSERT INTO employees (
 employee_id,
 full_name,
 manager_id
)
VALUES
 (1, 'M.S Dhoni', NULL),
 (2, 'Sachin Tendulkar', 1),
 (3, 'R. Sharma', 1),
 (4, 'S. Raina', 1),
 (5, 'B. Kumar', 1),
 (6, 'Y. Singh', 2),
 (7, 'Virender Sehwag ', 2),
 (8, 'Ajinkya Rahane', 2),
 (9, 'Shikhar Dhawan', 2),
 (10, 'Mohammed Shami', 3),
 (11, 'Shreyas Iyer', 3),
 (12, 'Mayank Agarwal', 3),
 (13, 'K. L. Rahul', 3),
 (14, 'Hardik Pandya', 4),
 (15, 'Dinesh Karthik', 4),
 (16, 'Jasprit Bumrah', 7),
 (17, 'Kuldeep Yadav', 7),
 (18, 'Yuzvendra Chahal', 8),
 (19, 'Rishabh Pant', 8),
 (20, 'Sanju Samson', 8);

表格是:

示例 1:

下面将帮助从表employee创建一个行类型变量sel_employee

do $$
declare
  sel_employee employees%rowtype;
begin
  -- select employee with id 6    
  select *  
  from employees
  into sel_employee
  where employee_id = 6;
   
  raise notice 'The employee name is % and the manager id is %',
     sel_employee.full_name,
     sel_employee.manager_id;
end; $$;

输出

示例 2:

以下将帮助从表employees 中创建一个行类型变量sel_employee ,其中包含2 列employee_idfull_name

do $$
declare
  sel_employee employees%rowtype;
begin
  -- select employee with id 12  
  select employee_id,full_name  
  from employees
  into sel_employee
  where employee_id = 12;
   
  raise notice 'The employee name is % and the length of the name is %',
     sel_employee.full_name,
     length(sel_employee.full_name);
end; $$;

输出