Create database using variable name

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • deja@chronofish.com

    #1

    Create database using variable name

    Hello,

    I am using an SQL script to create a temporary database backup. While
    there may be "other" or "better" ways to do this - I am really only
    asking if the syntax (with tweaking) is possible - and if so what it
    is.

    Here is a very stripped down version of what I'm trying to attempt:

    set @backUpName = 'myBackup';
    create database @backUpName;


    This throws a syntax error, but I don't know why.

    Thanks!
    CF

  • Malcolm Dew-Jones

    #2
    Re: Create database using variable name

    deja@chronofish .com wrote:
    : Hello,

    : I am using an SQL script to create a temporary database backup. While
    : there may be "other" or "better" ways to do this - I am really only
    : asking if the syntax (with tweaking) is possible - and if so what it
    : is.

    : Here is a very stripped down version of what I'm trying to attempt:

    : set @backUpName = 'myBackup';
    : create database @backUpName;

    : This throws a syntax error, but I don't know why.

    I thought I knew why, but wanted to confirm it. I googled the mysql SET
    command, and it had a link to "user variables".


    MySQL Reference Manual :: 9.3 User Variables

    ...
    User variables may be used where expressions are allowed. This
    does not currently include contexts that explicitly require a
    literal value

    In other words, things like
    SELECT * FROM table WHERE col1 = @a_value;
    will work but
    SELECT * FROM @table_name;
    will not work because the table name must be a literal value, not an
    expression.

    (caveat, mysql version not taken into account)


    --

    This programmer available for rent.

    Comment

    • Bill Karwin

      #3
      Re: Create database using variable name

      Malcolm Dew-Jones wrote:[color=blue]
      > User variables may be used where expressions are allowed. This
      > does not currently include contexts that explicitly require a
      > literal value
      >
      > In other words, things like
      > SELECT * FROM table WHERE col1 = @a_value;
      > will work but
      > SELECT * FROM @table_name;
      > will not work because the table name must be a literal value, not an
      > expression.[/color]

      Well, to be accurate, a table name is not a literal value. A table name
      is a reference to some schema object. A literal value is something like
      "abc" or 12.

      I would guess (without having tried it ;-) that the comment about
      literal values refers to contexts like the arguments of the LIMIT
      clause, which take literal integer values, but not expressions or
      parameters. That is, the following would not be permitted:
      SELECT * FROM table LIMIT @a, @b;

      Regards,
      Bill K.

      Comment

      Working...