22

I fairly new to mysql but have MS SQL experience.

Is it possible to declare variables and use while statement outside stored procedure?

I only found examples where guys doing like this

1. procedure created
2. execute proc
3. drop proc

Suggest me the right way

Volodymyr
  • 1,136
  • 3
  • 11
  • 28

1 Answers1

18

No, you cannot do it. You can use these statements only inside BEGIN...END clause.

So, it is possible in stored procedures/functions, triggers and events.

More information here - MySQL Compound-Statement Syntax.

Devart
  • 119,203
  • 23
  • 166
  • 186
  • 3
    This is... pretty much a deal breaker if you're trying to port a MS SQL app to mysql (for example). Out of interest then what's the right approach when you're writing a migration script and you need to SET a variable to the output of a query and then do something conditionally (e.g. if I have value 'foo' then insert value 'bar' and insert value 'pants') in another table? – bounav Jul 28 '17 at 15:51
  • To answer my own comment you can write `INSERT INTO Table1(ColA, ColB) SELECT ColC, ColD FROM Table2 WHERE ColE = 'foo';` then chain these queries. – bounav Jul 28 '17 at 16:03