Declaring and using MySQL varchar variables

前端 未结 4 849
醉话见心
醉话见心 2021-02-11 21:18

I\'m trying to do some simple manipulations with variables in MySQL 5.0 but I can\'t quite get it to work. I\'ve seen many (very!) different syntaxen for DECLARE/SET, I\'m not

相关标签:
4条回答
  • 2021-02-11 21:34

    This works fine for me using MySQL 5.1.35:

    DELIMITER $$
    
    DROP PROCEDURE IF EXISTS `example`.`test` $$
    CREATE PROCEDURE `example`.`test` ()
    BEGIN
    
      DECLARE FOO varchar(7);
      DECLARE oldFOO varchar(7);
      SET FOO = '138';
      SET oldFOO = CONCAT('0', FOO);
    
      update mypermits
         set person = FOO
       where person = oldFOO;
    
    END $$
    
    DELIMITER ;
    

    Table:

    DROP TABLE IF EXISTS `example`.`mypermits`;
    CREATE TABLE  `example`.`mypermits` (
      `person` varchar(7) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    
    INSERT INTO mypermits VALUES ('0138');
    
    CALL test()
    
    0 讨论(0)
  • 2021-02-11 21:41

    I ran into the same problem using MySQL Workbench. According to the MySQL documentation, the DECLARE "statement declares local variables within stored programs." That apparently means it is only guaranteed to work with stored procedures/functions.

    The solution for me was to simply remove the DECLARE statement, and introduce the variable in the SET statement. For your code that would mean:

    -- DECLARE FOO varchar(7); 
    -- DECLARE oldFOO varchar(7);
    
    -- the @ symbol is required
    SET @FOO = '138'; 
    SET @oldFOO = CONCAT('0', FOO);
    
    UPDATE mypermits SET person = FOO WHERE person = oldFOO;
    
    0 讨论(0)
  • 2021-02-11 21:52

    Looks like you forgot the @ in variable declaration. Also I remember having problems with SET in MySql a long time ago.

    Try

    DECLARE @FOO varchar(7);
    DECLARE @oldFOO varchar(7);
    SELECT @FOO = '138';
    SELECT @oldFOO = CONCAT('0', @FOO);
    
    update mypermits 
       set person = @FOO 
     where person = @oldFOO;
    
    0 讨论(0)
  • 2021-02-11 21:57

    try this:

    declare @foo    varchar(7),
            @oldFoo varchar(7)
    
    set @foo = '138'
    set @oldFoo = '0' + @foo
    
    0 讨论(0)
提交回复
热议问题