MYSQL 8 基本 *** 作之10 (实现for循环逐个遍历)

MYSQL 8 基本 *** 作之10 (实现for循环逐个遍历),第1张

SQL:结构化查询语言,包括数据定义语言(DDL)如:CREATE、DROP、ALTER等;数据 *** 作语言(DML)如:INSERT、UPDATE、DELETE之类;数据查询语言(DQL)如:SELECT语句;数据控制语言(DCL)如:GRANT、REVOKE、COMMIT、ROLLBACK等。

T-SQL:Transact-SQL,为SQL的语言的增强版,加入了程序语言中的if,while 等流程控制语法,同时可以使用函数功能

CREATE PROCEDURE init_reportUrl()

BEGIN

DECLARE s INT DEFAULT 0

DECLARE r_id bigint(10)

DECLARE report CURSOR FOR select distinct id as r_id FROM ReportHotLine

-- 声明当游标遍历完后将标志变量置成某个值

DECLARE CONTINUE HANDLER FOR NOT FOUND SET s=1

-- 打开游标

open report

-- 将游标中的值赋值给变量,注意:变量名不要和返回的列名同名,变量顺序要和sql结果列的顺序一致

fetch report into r_id

-- 当s不等于1,也就是未遍历完时,会一直循环

while s<>1 do

-- 执行业务逻辑

UPDATE wh_csyx . dy_pres30207800013_001_local a

JOIN ReportHotLine b ON a.gdId = b.ID

AND b.createtime = ( SELECT max( createtime ) FROM ReportHotLine WHERE ID = r_id )

SET blms = b.banliInfo where a.gdId =r_id

-- 将游标中的值再赋值给变量,供下次循环使用

fetch report into r_id

-- 当s等于1时表明遍历以完成,退出循环

end while

-- 关闭游标

close report

END

call init_reportUrl()

f exists (select * from dbo.sysobjects where id = object_id(N'[tb]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)

drop table [tb]

GO

--示例数据

create table [tb]([id] int identity(1,1),[pid] int,name varchar(20))

insert [tb] select 0,'中国'

union all select 0,'美国'

union all select 0,'加拿大'

union all select 1,'北京'

union all select 1,'上海'

union all select 1,'江苏'

union all select 6,'苏州'

union all select 7,'常熟'

union all select 6,'南京'

union all select 6,'无锡'

union all select 2,'纽约'

union all select 2,'旧金山'

go

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_id]') and xtype in (N'FN', N'IF', N'TF'))

drop function [dbo].[f_id]

GO

/*--树形数据处理

级别及排序字段

--邹建 2003-12(引用请保留此信息)--*/

/*--调用示例

--调用函数实现分级显示

select replicate('-',b.[level]*4)+a.name

from [tb] a,f_id()b

where a.[id]=b.[id]

order by b.sid

--*/

create function f_id()

returns @re table([id] int,[level] int,sid varchar(8000))

as

begin

declare @l int

set @l=0

insert @re select [id],@l,right(10000+[id],4)

from [tb] where [pid]=0

while @@rowcount>0

begin

set @l=@l+1

insert @re select a.[id],@l,b.sid+right(10000+a.[id],4)

from [tb] a,@re b

where a.[pid]=b.[id] and b.[level]=@l-1

end

return

end

go

--调用函数实现分级显示

select replicate('-',b.[level]*4)+a.name

from [tb] a,f_id()b

where a.[id]=b.[id]

order by b.sid

go

--删除测试

drop table [tb]

drop function f_id

go

/*--结果

中国

----北京

----上海

----江苏

--------苏州

------------常熟

--------南京

--------无锡

美国

----纽约

----旧金山

加拿大

--*/


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/8711836.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-20
下一篇 2023-04-20

发表评论

登录后才能评论

评论列表(0条)

保存