我有来自外部来源的数据,当它出现时以逗号分隔。我正在创建一个存储过程,将从已存在的插入触发器之前调用。存储过程将计算字符串中逗号的数量,循环多次迭代,抓取该索引的子字符串,即迭代2为字符串" abc,def,ghi"返回deg,然后在连接表中创建一个条目IF返回的内容将根据已知良好值的表进行验证。
DELIMITER $$
DROP PROCEDURE IF EXISTS `create_isbn_catalog_join_table`$$
CREATE PROCEDURE create_isbn_catalog_join_table(catalog VARCHAR(32),isbn CHAR(20))
BEGIN
SET @x = 1;
-- a crappy way to count substr within a string
SELECT (length(catalog)-length(replace(catalog,',',''))) INTO @catalog_count;
SET @catalog_count = @catalog_count + 1;
REPEAT
-- a crappy way to simulate php substr
SET @cat = '';
SELECT REPLACE(
SUBSTRING(
SUBSTRING_INDEX(catalog, ',', @x),
LENGTH(
SUBSTRING_INDEX(catalog, ',',@x -1)
) + 1
),
',','') INTO @cat;
set @cat1 = 'WX';
set @valid_catalog = 0 ;
IF EXISTS (select 1 from valid_catalogs where catalog = @cat) THEN
select count(*),@cat from valid_catalogs where catalog = @cat ;
select count(*),@cat1 from valid_catalogs where catalog = @cat1 ;
INSERT INTO iz_products_catalogs
(`isbn`,`catalog`)
VALUES
(isbn,@cat);
END IF;
SET @x = @x + 1 ;
UNTIL @x > @catalog_count END REPEAT;
END$$
DELIMITER ;
这里有什么奇怪的是以下我错误地传递了IF子句以确定循环中的当前目录是否有效;例如,正在运行的2个查询:
select count(*),@cat from valid_catalogs where catalog = @cat ;
select count(*),@cat1 from valid_catalogs where catalog = @cat1 ;
注意@cat来自子串选择,并且通过SET命令设置了@ cat1。两者都是2个char值,这些值不在有效的目录表中。返回值为:
+----------+------+
| count(*) | @cat |
+----------+------+
| 27 | WZ |
+----------+------+
1 row in set (0.00 sec)
+----------+-------+
| count(*) | @cat1 |
+----------+-------+
| 0 | WX |
+----------+-------+
1 row in set (0.00 sec)
WZ或WX都不在valid_catalogs表中。但是当使用@cat查询有效目录的计数时,它返回27(表中的总行数),该值应为零,因为没有' WZ'行。当使用@ cat1查询时,它会准确地返回0.