2015-08-25 119 views
0

是否有可能创建sql文件,它可以获取两个数字参数并在循环中使用它们,在每次迭代中,我们都会使用这两个参数替换为指令,并在循环结尾增加它们?创建动态mysql查询

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

编辑:考虑我想更新表名为邮政编码,我想用这种方式将新代码:
你得到两个参数是数字。 首先是例如启动代码:1000 二是连续的代码添加号码,让说5 所以,你将与1000,1001更新表... 1004

+1

您需要一个您想要做的事情的实例,包括数据和输出。 – Paul

+0

@Paul:添加示例 – JavaSa

+0

SQL不是过程语言。你可以使用扩展它的存储过程和一些控制结构。或者你可以“生成”数据,然后你可以选择你想要的结果。 – jkavalik

回答

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

我用这个在少数情况下产生:循环,但您可以通过生成一些数据,然后描述你想声明的方式与他们做什么“效仿”他们在某些日期之间的所有天(主要是为了填补数据f中的空白)或报告),即使我尝试了大数字,它的速度也非常快。但是如果你知道@count的最大值是多少,那么你可以使用那么多。