0

Is it possible to auto generate a number if nothing is supplied for a column in the table

#SurveyId,Name,PhoneNumber
1,David,071234234
1,John, NULL

expected output

#SurveyId,Name,PhoneNumber
1,David,071234234
1,John, 3274985AUTO

I would like to write a trigger for my table to carry out the auto generation option; i would like to use UUID() for auto generating number

syntax error:

15:10:23    CREATE TRIGGER mobilecheck BEFORE INSERT ON reg02_maininfo  `FOR EACH ROW IF NEW.farmermobile IS NULL THEN SET NEW.farmermobile = floor(rand()*900000)+100000   Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 2  0.0015 sec`
Mirieri Mogaka
  • 517
  • 4
  • 23

2 Answers2

1

You could do it this way

SELECT SurveyId, Name, IFNULL(PhoneNumber,floor(rand()*900000)+100000) as PhoneNumber FROM table

I did not add an AUTO at the end as if the field only accepts an integer it will give you an error.

You could also update your table to directly replace all null values

UPDATE Table SET PhoneNumber = floor(rand()*900000)+100000
WHERE PhoneNumber IS NULL;

For a trigger you could use the following :

CREATE TRIGGER phonecheck BEFORE INSERT ON tablename FOR EACH ROW IF NEW.PhoneNumber IS NULL THEN SET NEW.PhoneNumber = floor(rand()*900000)+100000; END IF;
Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57
-1

COALESCE to fetch it if it's non-null, FLOOR+RAND to get a random number otherwise, CONCAT to add AUTO at the end?

SELECT `#SurveyId`,`Name`,COALESCE(`PhoneNumber`,CONCAT((FLOOR(RAND()*(9999999-1000000+1))+1000000),'AUTO')) AS PhoneNumber
hanshenrik
  • 19,904
  • 4
  • 43
  • 89