创建动态mysql查询

时间:2015-08-25 18:52:49

标签: mysql

是否可以创建sql文件,它可以获得两个数字参数并在循环中使用它们,在每次迭代中我们使用这两个参数替换为指令,并在循环结束时递增它们?

有人可以告诉我该怎么做吗?

编辑:考虑我要更新表格命名的邮政编码,我想以这种方式插入新代码:
你得到两个数字参数。 第一个是起始代码,例如:1000 第二个是要添加的顺序代码的数量,比方说5。 因此,您将使用1000,1001 ... 1004

更新表格

1 个答案:

答案 0 :(得分:0)

SQL查询不能执行循环,但您可以通过生成一些数据“模拟”它们,然后以声明方式描述您要对它们执行的操作:

-- your input variables
set @start = 1000;
set @count = 5;

select val as zip from (
  -- generate some numbers starting with the value of @start
  select @start + (a.a + (10 * b.a) + (100 * c.a)) as val
    from (
      -- this creates cross join of 3 tables of numbers 0-9
      -- so the select up there gets rows with values 0-999
      -- you can add another cross join and 1000*d.a to get 0-9999
      select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
        cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
        cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
  ) tmp
-- we should generate enough numbers to always cover the needs
-- then this condition will filter only currently needed values
where (val >= @start) and (val < @start + @count)

http://sqlfiddle.com/#!9/9eecb7d/17037

上查看

我在少数情况下使用它来生成某些日期之间的所有日期(主要是为了填补报告数据的空白),即使我尝试了大数字,它也出乎意料地快。但如果你知道@count的最大值是什么,你可以使用那么多。