I am creating a stored procedure in my sql work bench. I am modifying the postcode of an address to format ‘dn35 7tg’ With a 7 character postcode even if the spaces are not inserted by the user.
Firstly I cannot find a way of printing the variables to the consol screen, which does not help my situation.
When running the Call statement
CALL usp_addsupplier('Bobs shopping mania', 'dn465th');
I except to find the values entered into the database with the correct formatting, however all I get is the PK, Null and Null entered in the columns.
If some could point me in the right direction I would be great full
Thank you all.
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
I am not great on MySQL, but there are a couple of errors that jump out at me.
Firstly, you never set
new_namebefore inserting it, so this will always be null.Secondly, I don’t think MySQL likes string concatenation using
StringA + StringB, you need to useCONCAT(StringA, StringB)Thirdly, There is a syntax error in your insert command (As pointed out by eggyal).
On a separate note however, your logic will not work to properly format UK Postcodes. For example, M1 1AA is a perfectly valid UK Postcode:
As you can see the “formatted” postcodes are a mess. You can achieve this in a much simpler manner using the INSERT function. UK postcodes are a variable number of characters (2-4) followed by a space followed by 3 characters.
The first step should be to cleanse the input (assummed to be @PostCode based on my test Fiddle)
this will remove all spaces, so it is irrelevant whether the raw input has spaces or not.
You then need to insert a space 3 characters from the end of the string. To find this position you use:
This gives an end result of:
So this can all be done in one call: