我正在我的sql工作台创建一个存储过程。我正在修改地址的邮政编码格式'dn35 7tg'使用7个字符的邮政编码,即使用户没有插入空格也是如此。
首先,我找不到将变量打印到consol屏幕的方法,这对我的情况没有帮助。
运行Call语句时
CALL usp_addsupplier('Bobs shopping mania', 'dn465th');
我除了使用正确的格式找到输入数据库的值,但我得到的只是在列中输入的PK,Null和Null。
如果有人能指出我正确的方向,我会很满意
谢谢大家。
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `usp_addsupplier`(IN SuppliersName VARCHAR(30), IN SuppliersPostCode VARCHAR(15))
BEGIN
-- Declare the change varables
DECLARE postcode VARCHAR(8) DEFAULT SuppliersPostCode;
SET postcode = SuppliersPostCode;
-- Postcode reformat -----------------------------------------------
-- Change postcode to uppercase
SET postCode = UPPER(postCode);
-- Grabs the first 4 letters and stores them in a new varable
SET new_postcode = LEFT (postCode,4);
-- Adds the space to the first 4 letters
SET new_postcode = new_postcode + ' ';
-- Add the last 3 letters to the new varable
SET new_postcode = new_postcode + RIGHT(postCode,3);
INSERT INTO tblsupplier (SupplierName, SupplierPostCode VALUES (new_name, new_postcode));
END
答案 0 :(得分:1)
我在MySQL上并不出色,但有一些错误会突然出现在我身上。
首先,在插入之前,你永远不会设置new_name
,所以这将永远为空。
其次,我不认为MySQL喜欢使用StringA + StringB
进行字符串连接,您需要使用CONCAT(StringA, StringB)
第三,插入命令中存在语法错误(正如eggyal所指出的那样)。
但是,单独注意,您的逻辑无法正确格式化英国邮政编码。例如,M1 1AA是完全有效的英国邮政编码:
M1 1AA --> M1 1 1AA
M11AA --> M11A 1AA
正如您所看到的,“格式化”的邮政编码是一团糟。您可以使用INSERT函数以更简单的方式实现此目的。英国邮政编码是可变数量的字符(2-4),后跟一个空格,后跟3个字符。
第一步应该是清理输入(根据我的测试Fiddle确定为@PostCode)
REPLACE(@PostCode, ' ', '');
这将删除所有空格,因此原始输入是否包含空格无关紧要。
然后,您需要在字符串末尾插入3个字符的空格。要找到这个位置,请使用:
CHAR_LENGTH(@PostCode) - 2
这给出了最终结果:
UPPER(INSERT(REPLACE(@PostCode, ' ', ''), CHAR_LENGTH(REPLACE(@PostCode, ' ', '')) - 2, 0, ' ')))
所以这一切都可以在一个电话中完成:
SET @SupplierName = 'Test';
SET @PostCode = 'M 1 1 A A ';
INSERT INTO tblSupplier (SupplierName, SupplierPostCode )
VALUES (@SupplierName, UPPER(INSERT(REPLACE(@PostCode, ' ', ''), CHAR_LENGTH(REPLACE(@PostCode, ' ', '')) - 2, 0, ' ')));
答案 1 :(得分:0)
INSERT
命令中存在语法错误:
INSERT INTO tblsupplier (SupplierName, SupplierPostCode VALUES (new_name, new_postcode));
应该是
INSERT INTO tblsupplier (SupplierName, SupplierPostCode) VALUES (new_name, new_postcode);
您需要DECLARE
变量new_name
和new_postcode
。
您需要为new_name
分配值。