我如何为学生分配用户名,使用他们的首字母后跟增加的数字?我不确定我的数据库中有多少学生,我希望他们的用户名看起来像“例如AC001,JD003。而且,如果有类似的首字母,我希望用户名继续按顺序递增。例如“AC001”和“AC002”
答案 0 :(得分:1)
您需要在BEFORE INSERT
事件和序列上使用触发器来实现此目的。
我假设您的表格如下:
TABLE user
( userid VARCHAR2(100) -- PRIMARY KEY COLUMN
, firstname VARCHAR2(100)
, lastname VARCHAR2(100)
, .... -- Other columns
);
按如下方式创建序列:
CREATE SEQUENCE sq_userid;
您将userid
列设置为null的行插入。
INSERT INTO user VALUES (null, 'Jack', 'Daniels', ....);
然后,您的触发器应如下所示:
CREATE OR REPLACE TRIGGER trg_user
BEFORE INSERT ON user
REFERENCING new AS new old AS old
FOR EACH ROW
BEGIN
IF :new.userid IS NULL THEN
:new.userid := UPPER(LEFT(firstname, 1))
|| UPPER(LEFT(lastname, 1))
|| TO_CHAR(sq_userid.nextval, '099');
END IF;
END;
/
触发器将'JD001'作为此实例中userid
的值。
有关详细信息,请Coding triggers,sequences和to_char。
答案 1 :(得分:0)
我认为这也会奏效 1st创建序列user_seq;
insert into user values('user_name'||user_seq.nextval);
您可以根据自己的要求修改上述查询。
答案 2 :(得分:0)
我摆弄了一个解决方案,但它在MySQL中。我相信你可以得到一般的想法并将其转换为Oracle(SQL Fiddle本身有一个Oracle 11g选项):http://sqlfiddle.com/#!2/e8ed5/1
<强>架构:强>
CREATE TABLE ALPHA_ROLL (
ALPHA1 CHAR(1),
ALPHA2 CHAR(1),
ROLL INTEGER,
PRIMARY KEY(ALPHA1, ALPHA2)
)//
CREATE TABLE user (
USERID VARCHAR(5),
FIRSTNAME VARCHAR(100),
LASTNAME VARCHAR(100),
PRIMARY KEY (USERID)
)//
CREATE TRIGGER trg_user
BEFORE INSERT ON user
FOR EACH ROW
BEGIN
SET @gen_user_id =
(SELECT CONCAT(ALPHA1,ALPHA2,LPAD((ROLL+1), 3, '0'))
FROM ALPHA_ROLL
WHERE ALPHA1 = UPPER(LEFT(NEW.firstname, 1))
AND ALPHA2 = UPPER(LEFT(NEW.lastname, 1))
LIMIT 1);
IF (@gen_user_id IS NULL) THEN
INSERT INTO ALPHA_ROLL (ALPHA1, ALPHA2, ROLL)
VALUES (UPPER(LEFT(new.firstname, 1)), UPPER(LEFT(new.lastname, 1)), 1);
SET @GEN_USER_ID =
CONCAT(UPPER(LEFT(new.firstname, 1)),
UPPER(LEFT(new.lastname, 1)),
'001');
ELSE
UPDATE ALPHA_ROLL SET ROLL = ROLL + 1
WHERE ALPHA1 = UPPER(LEFT(new.firstname, 1))
AND ALPHA2 = UPPER(LEFT(new.lastname, 1));
END IF;
SET new.userid = @GEN_USER_ID;
END//
<强> SQL:强>
INSERT INTO USER (FIRSTNAME, LASTNAME) VALUES ('Johnnie', 'Walker');
INSERT INTO USER (FIRSTNAME, LASTNAME) VALUES ('Jason', 'Mraz');
INSERT INTO USER (FIRSTNAME, LASTNAME) VALUES ('Mariah', 'Carrie');
INSERT INTO USER (FIRSTNAME, LASTNAME) VALUES ('Justin', 'Morg');
INSERT INTO USER (FIRSTNAME, LASTNAME) VALUES ('Matthew', 'Congoman');
INSERT INTO USER (FIRSTNAME, LASTNAME) VALUES ('Jack', 'Waltson');
INSERT INTO USER (FIRSTNAME, LASTNAME) VALUES ('Jojo', 'Wonderful');
SELECT * FROM USER;
SELECT * FROM ALPHA_ROLL;
<强>结果:强>
USERID FIRSTNAME LASTNAME
JM001 Jason Mraz
JM002 Justin Morg
JW001 Johnnie Walker
JW002 Jack Waltson
JW003 Jojo Wonderful
MC001 Mariah Carrie
MC002 Matthew Congoman
ALPHA1 ALPHA2 ROLL
J M 2
J W 3
M C 2