简体   繁体   中英

MySQL: how do I get a for loop from a comma separated list?

I want to create sqlstring, prepare stmt, execute stmt for a long list of integer values

for i in (6500,6700,15781,..,79865)
  for j in string values ("TT","FF","DD","RH")
     long .sql script;
  end for j
end for i

In Informix SQL it is like:

FOR i IN (1 TO 20 STEP 5, 20 to 1 STEP -5, 1,2,3,4,5)
. . .
END FOR:

see http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.sqlt.doc/sqltmst275.htm

I'm new to mysql and the syntax differs from what I'm used to. Creating a procedure seems to me a bit odd to get this working.

MySQL doesn't have an array type, and your list of integer values is a literal array, so there is no way to represent that list natively in MySQL, or indeed use it as a loop control.

You've basically two ways to solve this:

  • Either do it in app code, where you'll happily have syntax similar to that you present as an example
  • ...or express the problem as a query (for example a CROSS JOIN ) between two tables, each one containing the data in your literal array or list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM