如何格式化此MySQL存储过程?

时间:2019-05-10 18:49:03

标签: mysql stored-procedures

我在格式化此MySQL存储过程时遇到困难,我已经制作了mssql存储过程,但mysql一直给我问题。有经验的人可以看看并让我知道我缺少什么格式吗?

CREATE PROCEDURE dbo.spInsertPropertyAndUnit (
  IN AccountId INTEGER,
  IN Address VARCHAR(255),
  IN AddressNumber VARCHAR(255),
  IN City VARCHAR(255),
  IN State VARCHAR(255),
  OUT PropertyId INTEGER
)

BEGIN
  DECLARE PropertyId INTEGER;

  -- make property
  INSERT INTO tblProperties 
    (Address, AddressNumber, City, State)
  VALUES (
    IFNULL(Address, ''),
    IFNULL(AddressNumber, ''),
    IFNULL(City, ''),
    IFNULL(State, '')
  )
  SET PropertyId = CAST(SCOPE_IDENTITY() AS INTEGER)

  -- make a default unit
  INSERT INTO tblUnits (PropertyId, UnitNumber)
  VALUES (PropertyId, 1)

  -- Make an Accountpropertymembership
  INSERT INTO tblAccountPropertyMemberships (AccountId, PropertyId, MembershipRoleId)
  VALUES (AccountId, PropertyId, 0)

  SELECT PropertyId FROM tblProperties WHERE PropertyId = @PropertyId
END

1 个答案:

答案 0 :(得分:1)

获取最后一个自动增量ID的函数是LAST_INSERT_ID()

您不能使用@PropertyID来访问名为PropertyID的声明变量。同样,您不能使用@AccountID来访问AccountID参数。

您无需声明变量PropertyID,因为它已经被声明为OUT参数。

每个语句的末尾都需要;。使用DELIMITER指令指定备用查询定界符,因此您可以在过程中使用;

最后,您可以简单地使用SELECT PropertyId返回变量的值,而无需查询表本身。

DELIMITER $$
CREATE PROCEDURE dbo.spInsertPropertyAndUnit (
  IN AccountId INTEGER,
  IN Address VARCHAR(255),
  IN AddressNumber VARCHAR(255),
  IN City VARCHAR(255),
  IN State VARCHAR(255),
  OUT PropertyId INTEGER
)

BEGIN
  PropertyId INTEGER;

  -- make property
  INSERT INTO tblProperties 
    (Address, AddressNumber, City, State)
  VALUES (
    IFNULL(Address, ''),
    IFNULL(AddressNumber, ''),
    IFNULL(City, ''),
    IFNULL(State, '')
  );
  SET PropertyId = LAST_INSERT_ID();

  -- make a default unit
  INSERT INTO tblUnits (PropertyId, UnitNumber)
  VALUES (PropertyId, 1);

  -- Make an Accountpropertymembership
  INSERT INTO tblAccountPropertyMemberships (AccountId, PropertyId, MembershipRoleId)
  VALUES (AccountId, PropertyId, 0);

  SELECT PropertyId;
END
$$
DELIMITER ;