gpt4 book ai didi

mysql - 创建动态 mysql 查询

转载 作者:行者123 更新时间:2023-11-29 22:05:11 26 4
gpt4 key购买 nike

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

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

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

最佳答案

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 的最大值是多少,您就可以使用该值。

关于mysql - 创建动态 mysql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32211847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com