Set AUTO_INCREMENT value programmatically

前端 未结 4 2001
我在风中等你
我在风中等你 2021-01-06 05:20

So this works...

ALTER TABLE variation AUTO_INCREMENT = 10;

But I want to do this;

ALTER TABLE variation AUTO_INCREMENT = (         


        
相关标签:
4条回答
  • 2021-01-06 05:59

    I'm not familiar enough with mysql to give a specific answer. However, in other database engines, there's an EXEC method you can pass a string into that will be executed. You simply write a script that determines the value you want for the auto_increment, then insert that value as a string into the script that is EXEC'd. Basically writing a script that writes a second script and runs it.

    EDIT: Looks like you want a prepared statement. Search for 'Dynamic SQL' There's an almost duplicate here

    EDIT2: Tim, ref this link that is referred to in the almost duplicate StackOverflow post previously given. Search for the string 'Using Parameters' on the page, and you'll get the skinny on that. MySql makes this a little difficult apparently. In MSSqlServer 2000, this was a trivial process. Here is another link to an article about mysql dynamic sql

    0 讨论(0)
  • 2021-01-06 06:05

    I don't know if this is a good idea, but could you do it with 2 queries in a server side language, for example, PHP?

    $incrementStep = Db::query('SELECT MAX(id)+1 FROM old_db.varaition');
    
    Db::query('ALTER TABLE variation AUTO_INCREMENT = ' . (int) $incrementStep);
    

    Assuming that Db::query is a magic query method that returns exactly what you want, every time :)

    0 讨论(0)
  • 2021-01-06 06:19

    Set your auto_increment in 1, zero doesn't work, automatically mysql set the maximum value to the next value for index value.

    ALTER TABLE table AUTO_INCREMENT = 1
    
    0 讨论(0)
  • 2021-01-06 06:25

    You can dynamically inject static value to a dynamic SQL call as in:

    SET @minEmptyId := 1337;
    CALL statement(CONCAT('
      ALTER TABLE tableName
      AUTO_INCREMENT = ', @minEmptyId))
    ;
    

    statement procedure implementation:

    DELIMITER $$
    CREATE PROCEDURE statement(IN dynamic_statement TEXT)
    BEGIN
          SET @dynamic_statement := dynamic_statement;
          PREPARE prepared_statement FROM @dynamic_statement;
          EXECUTE prepared_statement;
          DEALLOCATE PREPARE prepared_statement;
      END$$
    DELIMITER ;
    
    0 讨论(0)
提交回复
热议问题