首页 > 解决方案 > SQL 获取用户输入并进一步使用它

问题描述

我有将新记录插入 table 的任务EMPLOYEES。我知道如何通过要求用户输入一个值来做到这一点,例如:

INSERT INTO EMPLOYEES (first_name, last_name, email, hire_date, job_id)
VALUES ('&first_name', '&last_name', '&email' ,'&hire_date', 'SA_REP' );

但是,我不想询问用户,email而是通过将输入的第一个字母与将其数据添加到表中的人的first_name连接来自动插入它。last_name为了做到这一点,我想我必须暂时存储插入的值,或者至少获得一些对first_nameand的引用last_name。我尝试在网上搜索,但真的一无所获。你能为我提供这个任务的最简单的解决方案吗?我正在使用 Oracle SQL Developer。

标签: sqloracleoracle-sqldevelopersql-insert

解决方案


您可以将其包装在 PL/SQL 块中,以使用具有正确数据类型的适当变量。这也将确保以date 正确的格式正确输入变量的值。

DECLARE
v_first_name employees.first_name%type := '&first_name';
v_last_name  employees.last_name%type  := '&last_name';
v_hire_date  employees.hire_date%type  := TO_DATE('&hire_date_YYYYMMDD','YYYYMMDD');
BEGIN

INSERT INTO EMPLOYEES (first_name, last_name, email, hire_date, job_id)
VALUES (v_first_name, v_last_name, 
      substr(v_first_name,1,1)||'.'||v_last_name , v_hire_date, 'SA_REP' );
      --first letter of the first_name with last name
END;
/

结果

Enter value for first_name: John
Enter value for last_name: Doe
Enter value for hire_date_YYYYMMDD: 20190521
..
..
PL/SQL procedure successfully completed.

推荐阅读