我是使用mysql的新数据库。我有两个表州和国家,其中countryid是州表中的外键。我有一个可以添加状态的场景,并且在添加假设该国家变成新的状态时,则必须在国家/地区表上执行插入操作。我的问题是我正在浏览各种文档而且我发现而不是从java端编写每个查询,它总是考虑将所有内容组织到存储过程中,所以我已经开始这样做了。
CREATE DEFINER=`pratyush`@`%` PROCEDURE `ADD_STATE`(in statename varchar(45), in countryname varchar(45)) BEGIN declare countryIdd varchar(45); if (!checkNull(statename) AND !checkNull(countryname)) then if exists (select country_id from ems.country where country_name = countryname) then if not exists (select state_id from ems.state where state_name = statename) then select country_id into countryidd from ems.country where country_name = countryname; insert into ems.state(state_name, country_id) values(statename, countryidd); end if; end if; end if; END
如果我出错了,请告诉我。提前谢谢。
答案 0 :(得分:0)
CREATE DEFINER=`pratyush`@`%` PROCEDURE `ADD_STATE`(in statename varchar(45), in countryname varchar(45))
BEGIN
declare countryIdd varchar(45);
if (!checkNull(statename) AND !checkNull(countryname)) then
if exists (select country_id from ems.country where country_name = countryname) then
if not exists (select state_id from ems.state where state_name = statename) then
select country_id into countryidd from ems.country where country_name = countryname;
insert into ems.state(state_name, country_id) values(statename, countryidd);
end if;
end if;
if not exists (select countryid from country where countryname = @countryname) then
if not exists (select stateid from state where statename = statename) then
insert into ems.country(country_id,country_name) values(countryidd, countryname);
select country_id into countryidd from ems.country where country_name = countryname;
insert into ems.state(state_name, country_id) values(statename, countryidd);
end if;
end if;
end if;
END
对您的代码进行某些更改。我认为你必须添加另一个条件来检查国家是否存在以及是否不插入该表。您唯一需要做的就是添加一个方法来查找要插入的下一个国家/地区ID并将其存储在countryid中。如果countryid字段为int且auto increment,则无需查找id只需插入countryname,它将自动递增到下一个值。如果答案没有用,那么提前抱歉