Sql自动输入我合并的列

时间:2016-02-18 14:25:22

标签: mysql sql concatenation concat

我有列Fname和Lname以及全名。

我想创建一个函数,当我输入Fname和Lname时,它出现在列Full Name中。

enter image description here

CREATE DEFINER=`root`@`localhost` FUNCTION `inser_customer`(Cname VARCHAR(50), CMname VARCHAR(50),CLname VARCHAR(50), edad VARCHAR(50), sex VARCHAR(50), brgay VARCHAR(50), sity VARCHAR(50), Cno VARCHAR(50), gmail VARCHAR(50)) RETURNS VARCHAR(50) CHARSET latin1
BEGIN
SET @full=(SELECT GROUP_CONCAT(Fname,' ', Lname) FROM customer);

IF EXISTS (SELECT * FROM customer WHERE Fname = Cname AND Lname = CLname)THEN
RETURN "Customer Already Exists";
ELSE INSERT INTO customer (`Fname`,`Mname`,`Lname`,`Birthdate`,`Gender`,`Brgy`,`City`,`ContactNo`,`Email`,`Full Name`)VALUES(Cname, CMname, CLname, edad, sex, brgay, sity, Cno, gmail, @full2);
RETURN "OK";
END IF;
    END$$

感谢。

2 个答案:

答案 0 :(得分:0)

您需要使用Trigger

See here

  

触发器是与表关联的命名数据库对象,并在表发生特定事件时激活。触发器的一些用途是执行对要插入表中的值的检查,或者对更新中涉及的值执行计算。

插入新行后

delimiter //
CREATE TRIGGER full_name_after_insert AFTER INSERT ON customer
FOR EACH ROW
SET NEW.`Full Name` = CONCAT(NEW.`Fname`, " ",NEW.`Lname`)
END;//
delimiter ;

我建议您在更新现有行后获得触发器以获得更好的一致性和维护

delimiter //
CREATE TRIGGER full_name_after_update AFTER UPDATE ON customer
FOR EACH ROW
SET NEW.`Full Name` = CONCAT(NEW.`Fname`, " ",NEW.`Lname`)
END;//
delimiter ;

答案 1 :(得分:0)

我建议您首先尝试类似于单元测试的功能,然后根据您的需要进行调整:

CREATE TABLE `test` (
  `firstname` varchar(20) DEFAULT NULL,
  `lastname` varchar(20) DEFAULT NULL,
  `fullname` varchar(40) DEFAULT NULL
);

然后创建函数:

delimiter //

create function insert_test_data (
  mFirstname varchar(20),
  mLastname varchar(20)
)
returns varchar(50)
begin
  set @fullname = trim( concat( trim(mFirstname), ' ', trim(mLastname) ) );

  if exists (
    select 1 from test
    where firstname = mFirstname
          and lastname = mLastname
  ) then
    return 'Customer already exists';
  else
    insert into test (firstname, lastname, fullname) values
    (mFirstname, mLastname, @full);
    return 'OK';
  end if;

end //

delimiter ;

要插入数据:

select insert_test_data ('john', 'smith');
+------------------------------------+
| insert_test_data ('john', 'smith') |
+------------------------------------+
| OK                                 |
+------------------------------------+

select * from test;
+-----------+----------+----------+
| firstname | lastname | fullname |
+-----------+----------+----------+
| john      | smith    | NULL     |
+-----------+----------+----------+

如果客户已经存在,您将获得此信息:

select insert_test_data ('john', 'smith');
+------------------------------------+
| insert_test_data ('john', 'smith') |
+------------------------------------+
| Customer already exists            |
+------------------------------------+

建议:

我建议您不要添加计算字段。您只需输入名字和姓氏即可。在提取数据时,只需执行以下操作:

select trim( concat( trim(firstname), ' ', trim(lastname) ) )
from test;

因此,您可以即时使用此信息。