0

我真的希望你能帮我解决这个问题。我正在尝试根据旧字段长度是否大于一个来运行两种不同的更新查询。这背后的想法是,当用户更新产品时,它会将 ProductRef 附加到纯粹用于搜索的搜索表中。

很简单,如果 ProductRef 的字符串长度大于 0,则将旧的产品 ref 替换为新的。否则,添加新产品参考。这是我到目前为止所拥有的,但它似乎触发了一个错误 -

-- Update the ProductType UpdatedTS that corresponds with this product
-- The below section simply updates the main products UpdatedTS
UPDATE tbl_product_types 
SET UpdatedTS = now() 
WHERE ID = New.ProductTypeID;

IF ( SELECT Length(Old.ProductRef) > 0 )
    BEGIN
        -- We have already stored the product reference so run a replace
        UPDATE tbl_product_type_search AS STable
        SET `STable.Search` = replace(`Search`,CONCAT(Old.ProductRef,' '),New.ProductRef) 
        WHERE `STable.ProductTypeID` = Old.ProductTypeID
    END
ELSE
    BEGIN
        -- We haven't yet stored the product reference, store it
        UPDATE tbl_product_type_search AS STable
        SET `STable.Search` = CONCAT(NEW.ProductRef,' ',`STable.Search`) 
        WHERE STable.ProductTypeID = New.ProductTypeID
    END

供您参考,以下是相关的数据库结构:

数据库结构

4

2 回答 2

1

它似乎是 UPDATE 触发器。不是吗?如果是这样,试试这个代码(有一些语法错误) -

  UPDATE
    tbl_product_types
  SET
    UpdatedTS = NOW()
  WHERE ID = NEW.ProductTypeID;

  IF (SELECT length(Old.ProductRef) > 0) THEN
    -- We have already stored the product reference so run a replace
    UPDATE
      tbl_product_type_search AS STable
    SET
      `STable.Search` = REPLACE(`Search`, CONCAT(Old.ProductRef, ' '), NEW.ProductRef)
    WHERE
      `STable.ProductTypeID` = OLD.ProductTypeID;
  ELSE
    -- We haven't yet stored the product reference, store it
    UPDATE
      tbl_product_type_search AS STable
    SET
      `STable.Search` = CONCAT(NEW.ProductRef, ' ', `STable.Search`)
    WHERE
      STable.ProductTypeID = NEW.ProductTypeID;
  END IF;

两个 UPDATE 语句合二为一:

UPDATE
  tbl_product_type_search AS STable
SET
  `STable.Search` =
    IF(
      LENGTH(OLD.ProductRef) > 0,
      REPLACE(`Search`, CONCAT(OLD.ProductRef,' '), NEW.ProductRef),
      CONCAT(NEW.ProductRef, ' ', `STable.Search`)
    )
WHERE
  LENGTH(OLD.ProductRef) > 0 AND `STable.ProductTypeID` = OLD.ProductTypeID
  OR
  LENGTH(OLD.ProductRef) <= 0 AND STable.ProductTypeID = NEW.ProductTypeID

关于分隔符:

DELIMITER $$

CREATE TRIGGER trigger_name
AFTER UPDATE
ON table_name
FOR EACH ROW
BEGIN

  UPDATE tbl_product_types...;

  other statements...;
END
$$

DELIMITER ;
于 2012-07-25T09:44:21.823 回答
0

以下是未经测试的更新 if 语句。你可以试试看。

UPDATE tbl_product_type_search AS STable 
inner join tbl_product_type_search as Old on STable.ID=Old.ID 
SET `STable.Search` = 
     IF(Length(Old.ProductRef) > 0  AND `STable.ProductTypeID` = Old.ProductTypeID,   
        replace(`Search`,CONCAT(Old.ProductRef,' '),New.ProductRef),  
        IF(Length(Old.ProductRef) < 0 AND STable.ProductTypeID = New.ProductTypeID, 
          CONCAT(NEW.ProductRef,' ',`STable.Search`) ,`STable.Search` ));
于 2012-07-25T09:44:20.393 回答