PL/SQL基础(1):语法

2023-05-16

本篇是 Oracle基础小结 系列之一。


本篇目录

1、什么是PL/SQL?

2、PL/SQL基本结构

3、PL/SQL符号定义

4、PL/SQL数据类型

5、PL/SQL条件句法

6、PL/SQL循环


什么是PL/SQL?

PL/SQL有两重含义,一是指PL/SQLDeveloper,是一个集成开发环境(IDE),专门开发面向Oracle数据库的应用(程序);另外也是一种程序语言,叫做过程化SQL语言(ProceduralLanguage/SQL)。下面讲的都是后者PL/SQL,它是Oracle数据库对SQL语句的扩展。在普通SQL语句的使用上增加了编程语言的特点,所以PL/SQL把数据操作和查询语句组织在PL/SQL代码的过程性单元(也叫PL/SQL体)中,通过逻辑判断、循环等操作实现复杂的功能或者计算。PL/SQL只有 Oracle数据库有。MySQL等目前不支持 PL/SQL的。

初步了解PL/SQL移步https://en.wikipedia.org/wiki/PL/SQL,想比较系统的学习移步http://www.tutorialspoint.com/plsql。另外,学习SQL移步http://beginner-sql-tutorial.com,国内初步学习SQL的网站移步http://www.w3cschool.cn/sql,http://www.phpstudy.net/e/sql/sql_intro.html。有点扯远了,下面回归PL/SQL

引用:

http://baike.baidu.com/link?url=_NBUf3gNxzNLNpAUkarTWsYxFHQ6t6hUS1V9TwJ3uqrD-5A9CQWhSe26IzY49oaoWlZm5aeIWIxYPniE14s8Pa

 

PL/SQL基本结构

PL/SQL是块结构的语言,每个块包括(但不全部包括)三部分:声明、可执行命令、异常处理。可执行命令是必须的。可执行命令包含在一个BEGIN END;体里。他们基本结构是:

DECLARE

  <declarations section>      --变量、常量、游标、用户定义异常的声明

BEGIN

  <executable command(s)>         --SQL语句和PL/SQL语句构成的执行程序

EXCEPTION

  <exception handling>         --程序出现异常时,捕捉异常并处理异常

END;

下面是一个'Hello World' 例子,注意最后有 / :

DECLARE

  message  varchar2(20):= 'Hello,World!';

BEGIN

  dbms_output.put_line(message);

END;

/

引用:

http://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm

 

PL/SQL符号定义

         对于不怎么写SQL或者习惯MySQL的人,有一些符号需要注意:

单引号‘’           字符串

双引号“”          关键/预留词转义

PS:关键/预留词移步http://docs.oracle.com/cd/B10501_01/appdev.920/a42525/apb.htm

--                单行注释

=                等于比较,不是赋值

:=               赋值

注意,在PL/SQL Developer脚本里多个单元(单元是指建表、存储过程等,后续有介绍)之间要用 / 分隔,才能一次执行完,不然会报错。另外,虽然/*This is comment*/是多行注释,但是不能任性的写成/* //This is comment //*/这种出现//的情况,会导致多个PL/SQL单元在PL/SQLDeveloper中执行中断。

附各种符号(Delimiters)的描述:

+, -, *, /    Addition,subtraction/negation, multiplication, division

%      Attributeindicator

'        Characterstring delimiter

.        Componentselector

(,)     Expressionor list delimiter

:        Hostvariable indicator

,        Itemseparator

"       Quotedidentifier delimiter

=       Relationaloperator

@     Remoteaccess indicator

;        Statementterminator

:=      Assignmentoperator

=>     Associationoperator

||     Concatenationoperator

**     Exponentiationoperator

<<, >>       Label delimiter (begin and end)

/*, */        Multi-linecomment delimiter (begin and end)

--       Single-linecomment indicator

..       Rangeoperator

<, >, <=, >=       Relational operators

<>, '=, ~=, ^=    Different versions of NOT EQUAL

引用:

http://www.tutorialspoint.com/plsql/plsql_basic_syntax.htm

 

PL/SQL数据类型

PL/SQL的数据类型有4类:标量(Scalar)、大对象(LargeObject (LOB))、混合(Composite)和引用(Reference)。常用的是标量(数值、日期、布尔、字符或字符串等)、大对象(文本、图像、音频、视频等)。

Category

Description

Scalar

Single values with no internal components, such as a NUMBER, DATE, Character, or BOOLEAN.

Large Object (LOB)

Pointers to large objects that are stored separately from other data items, such as text, graphic images, video clips, and sound waveforms.

Composite

Data items that have internal components that can be accessed individually. For example, collections and records.

Reference

Pointers to other data items.

         标量(Scalar)包含4种数据类型(数值、日期、布尔、字符或字符串),每种数据类型又包含子数据类型。例如INTEGER是NUMBER类型的一种子类型。子类型使得PL/SQL可以同其他编程语言在数据类型上相兼容。

         PL/SQL数值型数据类型和子类型包括:

Data Type

Description

PLS_INTEGER

Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits

BINARY_INTEGER

Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32 bits

BINARY_FLOAT

Single-precision IEEE 754-format floating-point number

BINARY_DOUBLE

Double-precision IEEE 754-format floating-point number

NUMBER(prec, scale)

Fixed-point or floating-point number with absolute value in range 1E-130 to (but not including) 1.0E126. A NUMBER variable can also represent 0.

DEC(prec, scale)

ANSI specific fixed-point type with maximum precision of 38 decimal digits.

DECIMAL(prec, scale)

IBM specific fixed-point type with maximum precision of 38 decimal digits.

NUMERIC(pre, secale)

Floating type with maximum precision of 38 decimal digits.

DOUBLE PRECISION

ANSI specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)

FLOAT

ANSI and IBM specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)

INT

ANSI specific integer type with maximum precision of 38 decimal digits

INTEGER

ANSI and IBM specific integer type with maximum precision of 38 decimal digits

SMALLINT

ANSI and IBM specific integer type with maximum precision of 38 decimal digits

REAL

Floating-point type with maximum precision of 63 binary digits (approximately 18 decimal digits)

         PL/SQL字符型数据类型和子类型包括:

Data Type

Description

CHAR

Fixed-length character string with maximum size of 32,767 bytes

VARCHAR2

Variable-length character string with maximum size of 32,767 bytes

RAW

Variable-length binary or byte string with maximum size of 32,767 bytes, not interpreted by PL/SQL

NCHAR

Fixed-length national character string with maximum size of 32,767 bytes

NVARCHAR2

Variable-length national character string with maximum size of 32,767 bytes

LONG

Variable-length character string with maximum size of 32,760 bytes

LONG RAW

Variable-length binary or byte string with maximum size of 32,760 bytes, not interpreted by PL/SQL

ROWID

Physical row identifier, the address of a row in an ordinary table

UROWID

Universal row identifier (physical, logical, or foreign row identifier)

         PL/SQL日期型数据类型和子类型包括:

Field Name

Valid Datetime Values

Valid Interval Values

YEAR

-4712 to 9999 (excluding year 0)

Any nonzero integer

MONTH

01 to 12

0 to 11

DAY

01 to 31 (limited by the values of MONTH and YEAR, according to the rules of the calendar for the locale)

Any nonzero integer

HOUR

00 to 23

0 to 23

MINUTE

00 to 59

0 to 59

SECOND

00 to 59.9(n), where 9(n) is the precision of time fractional seconds

0 to 59.9(n), where 9(n) is the precision of interval fractional seconds

TIMEZONE_HOUR

-12 to 14 (range accommodates daylight savings time changes)

Not applicable

TIMEZONE_MINUTE

00 to 59

Not applicable

TIMEZONE_REGION

Found in the dynamic performance view V$TIMEZONE_NAMES

Not applicable

TIMEZONE_ABBR

Found in the dynamic performance view V$TIMEZONE_NAMES

Not applicable

PL/SQL大对象(LOB)数据类型用于存储诸如文本、图像、音频和视频等大数据条目,BLOB存储二进制文件(图像等),CLOB存储文本文件。具体包括:

Data Type

Description

Size

BFILE

Used to store large binary objects in operating system files outside the database.

System-dependent. Cannot exceed 4 gigabytes (GB).

BLOB

Used to store large binary objects in the database.

8 to 128 terabytes (TB)

CLOB

Used to store large blocks of character data in the database.

8 to 128 TB

NCLOB

Used to store large blocks of NCHAR data in the database.

8 to 128 TB

引用:

http://www.tutorialspoint.com/plsql/plsql_data_types.htm

 

PL/SQL条件

PL/SQL条件句法有IF-THEN-ELSIFCASE两种结构,两者可以互换。下面是IF-THEN-ELSIF结构的示例,其中ELSIF ELSE部分是可选的,因此可以简化成IF-THEN or, IF-THEN-ELSE结构。

IF x = 1 THEN

  sequence_of_statements_1;

ELSIF x = 2 THEN

  sequence_of_statements_2;

ELSIF x = 3 THEN

  sequence_of_statements_3;

ELSE

  sequence_of_statements_N;

END IF;

以下的CASE结构等价于上面的IF-THEN-ELSIF结构:

CASE

   WHENx = 1 THEN sequence_of_statements_1;

   WHENx = 2 THEN sequence_of_statements_2;

   WHENx = 3 THEN sequence_of_statements_3;

   ELSEsequence_of_statements_N;

END CASE;

         CASE结构在选择条件已知的情况下可以简化为如下结构,类似于其它语言的switch。

CASE x

   WHEN1 THEN sequence_of_statements_1;

   WHEN2 THEN sequence_of_statements_2;

   WHEN3 THEN sequence_of_statements_3;

   ELSEsequence_of_statements_N;

END CASE;

引用:

https://en.wikipedia.org/wiki/PL/SQL#Conditional_statements

 

PL/SQL循环

PL/SQL循环有4种:基础(Basic)、FOR、WHILE和嵌套(Nested)循环。

Loop Type

Description

PL/SQL Basic LOOP

In this loop structure, sequence of statements is enclosed between the LOOP and END LOOP statements. At each iteration, the sequence of statements is executed and then control resumes at the top of the loop.

PL/SQL WHILE LOOP

Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.

PL/SQL FOR LOOP

Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.

Nested loops in PL/SQL

You can use one or more loop inside any another basic loop, while or for loop.

         基础循环语句中需要额外的EXIT或EXIT WHEN来中断循环,相当于其他语言的Break。

LOOP

 Sequence of statements;

END LOOP;

         WHILE循环在条件满足时一直执行。

WHILE condition LOOP

  sequence_of_statements;

END LOOP;

         FOR循环有两种用法,一是从初始值到结束值循环一段范围,格式:

FOR counter IN initial_value .. final_valueLOOP

  sequence_of_statements;

END LOOP;

例如:

for i in 0..9 loop  

dbms_output.put_line('i:' || i);  

end loop;  

另一种用法是遍历隐式游标,例如:

for currow in ( 

select t.col1,t.col2 

from tableNamet 

where ... 

) loop 

if currow.col1 =0 then 

return;    -- 中止,返回 

end if; 

end loop;

引用:

http://www.tutorialspoint.com/plsql/plsql_loops.htm

http://wen866595.iteye.com/blog/1733887

 


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PL/SQL基础(1):语法 的相关文章

  • 将 List 保存到 ASP.NET 中的会话

    购物车项目保存在 SQL 数据库中 我想将所有 CartItems 放在一个 List 中并转移到 Instance Items The Instance变量正在保存到会话中 代码如下 public class ShoppingCart p
  • SQL 连接中的多个条件

    如何指定多个条件SQL加入 我知道A key B key除此之外是强制性的 以下对于指定多个条件是否正确SQL ON A key B key and or cond1 and or cond2 etc OR ON A key B key w
  • 在自引用表中查询父项和子项

    我有一个Comments如下表所示 在MySQL content created at id parent id second comment 2014 06 03T10 08 44 0000 37 1 third comment 2014
  • SQL 数据范围最小值最大值类别

    我想确定 2 个类别的范围 A 类和 B 类 A 从 1 到 15 开始 B 从 16 到 31 开始 然后 A 再次从 32 到 40 开始 现在如果运行此查询 select min range max range from table
  • 为什么 T-SQL 块即使不应该执行也会给出错误?

    我正在编写一个 看似 直接的 SQL 片段 它在确保列存在后删除该列 问题 如果该列不存在 则代码insideIF 子句抱怨它找不到该列 出色地 doh 这就是为什么它位于 IF 子句内 所以我的问题是 为什么一段不应该执行的代码会出错 这
  • PostgreSQL 索引使用分析

    是否有工具或方法可以分析 Postgres 并确定应创建哪些缺失的索引 以及应删除哪些未使用的索引 我在使用 SQLServer 的 分析器 工具执行此操作方面有一些经验 但我不知道 Postgres 中是否包含类似的工具 我喜欢这样来查找
  • postgresql 中带有分组的嵌套聚合函数

    我正在尝试使用嵌套聚合函数和分组来获得总和的平均值 我想做的是 SELECT AVG SUM x GROUP BY y WHERE GROUP BY 也就是说 对于返回的每一行 我希望其中一个字段是总和的平均值 其中每个总和都位于 y 相同
  • 如何在 WHERE 子句中最佳地使用 COALESCE() ?

    这是我的查询 select coalesce qa2 subject qa subject as question subject qa body select count from viewed items vi where coales
  • 字段名称来自表 1 上的 ID,但来自其他表上的名称

    这是一个 Firebird 数据库 第一张表 联系人 Company ID 职位名称 第二个表 Client id 公司名称 在联系人中 我希望 job title 字段包含 co name client id 和 company id 相
  • 使用 Oracle 中的 Join 查询进行更新

    查询有什么问题 它无限期地执行 UPDATE table1 t1 SET t1 col t1 Output SELECT t2 col t3 Output t2 col FROM tabl2 t3 LEFT JOIN table1 t2 O
  • 是否可以使用不在 GROUP BY 中的 ORDER BY 列?

    正如标题所说 这是我的代码 SELECT material SUM Amount AS Amount RIGHT CONVERT varchar 50 date in 106 8 FROM rec stats GROUP BY materi
  • 在 CASE 语句中使用 CAST 时出现数据转换错误

    运行以下命令时出现错误 将数据类型 nvarchar 转换为 float 时出错 declare completeCommand nvarchar max x paramVal nvarchar 100 paramName nvarchar
  • 在 SQL where 子句中使用带有 IsDate 的 case 语句

    我正在尝试清理以下代码中的 where 子句语句 SELECT CONVERT datetime UTC Time Stamp 127 AS TimeStamp FROM Table WHERE CASE WHEN ISDATE UTC T
  • 从多行中选择数据并对其进行排序[重复]

    这个问题在这里已经有答案了 id title content class 1 t1 p1 1 2 t2 p6 1 3 t3 p5 2 4 t4 p8 3 对于这个表 我如何使用 1 个查询来SELECT所有课程DISTINCTLY变成这个
  • 搜索并替换字符串 t-SQL

    每个人我都试图编写一个查询来替换末尾出现的所有字符串 我有一些干扰词 确切地说是 104 个 如果它们出现在字符串末尾 则需要将其从字符串中删除 例如 两个干扰词是 Company LLC 以下是一些示例和预期输出 American Com
  • 返回动态列集

    我创建了以下函数来根据该函数的参数返回列集 CREATE OR REPLACE FUNCTION getColumns IN column1 text IN column2 text IN column3 text IN column4 t
  • 为什么我的层次结构查询显示重复记录?

    我的要求是找到一个月中所有过去的天数 以下是我的示例查询 CREATE TABLE custom date full sno NUMBER curr date DATE INSERT INTO custom date full VALUES
  • SQL 层次结构 - 解析给定节点的所有祖先的完整路径

    我有一个由邻接列表描述的层次结构 不一定有单个根元素 但我确实有数据来识别层次结构中的叶 终端 项 所以 一个看起来像这样的层次结构 1 2 4 7 3 5 6 8 9 将通过表格来描述 就像这样 NOTE 我没有能力改变这种格式 id p
  • WCF 模拟和 SQL 可信连接?

    我们有一个托管在 IIS7 下的服务 SQL 服务器的连接字符串设置为 受信任 为了进行身份验证 我需要在服务上设置模拟并让客户端启动模拟连接 有没有办法不设置模拟并仍然允许服务通过可信连接登录到 SQL Server 我们希望避免让客户端
  • db2:使用不同表上的选择更新多行和字段

    对于 A 的所有行 其中 A x B z 是否可以使用不同表 B c B d 的值 c 和 d 来增加表 A a 和 A b 的字段 a 和 b 我对这个查询感到疯狂 DB2 和 SQL 标准在 UPDATE 语句中没有 FROM 子句 所

随机推荐

  • np.meshgrid()与torch.meshgrid()的区别

    比如要生成一张图像 h 61 6 w 61 10 的xy坐标点 xff0c 看下两者的实现方式 xff1a 两种方式的差异在于 xff1a xs ys 61 np meshgrid np arange w np arange h xs ys
  • JSON是什么

    提起 JSON xff0c 作为如今最受欢迎的数据交换格式 xff0c 可以说是无人不知 无人不晓了 JSON 全称 JavaScript Object Notation xff08 JS 对象简谱 xff09 xff0c 自诞生之初的小目
  • 【C++】数组定义引发Stack overflow错误(运行时是报段错误)

    C 43 43 xff08 实际是C的语法 xff09 定义数组时出错 xff0c 代码如下 xff1a float t1 9830400 调试时触发Stack overflow错误 xff08 可执行文件运行时 xff0c 是报段错误 x
  • 【C/C++】数组初始化

    数组定义不初始化会被随机赋值 因此如果数组的所有元素在下面没有逐一赋值 xff0c 但是又会使用到的话 xff0c 最后不要只定义而不初始化 会带来问题 数组初始化的几种形式 可以直接用 xff1a a 10 61 xff0c 就可以让a
  • 【C++】指针数组与数组指针

    指针数组 指针数组可以说成是 指针的数组 xff0c 首先这个变量是一个数组 xff0c 其次 xff0c 指针 修饰这个数组 xff0c 意思是说这个数组的所有元素都是指针类型 xff0c 在32位系统中 xff0c 指针占四个字节 定义
  • 【旋转框目标检测】2201_The KFIoU Loss For Rotated Object Detection

    paper with code paper code Jittor Code https github com Jittor JDet PyTorch Code https github com open mmlab mmrotate Te
  • CUDA编译报错unsupported GNU version! gcc versions later than 10 are not supported!

    问题 xff1a python编译用于cuda的so文件中 xff0c 使用编译 cu文件出错 xff1a error unsupported GNU version gcc versions later than 10 are not s
  • RuntimeError: CUDA error: no kernel image is available for execution on the device

    问题 xff1a 代码换机器执行时 xff0c 使用包含自行编译的cuda算子库so时出错 xff1a RuntimeError CUDA error no kernel image is available for execution o
  • Ubuntu非LTS版本安装nvidia-docker出错:Unsupported distribution!

    问题 xff1a 按照Nvidia官方流程 xff0c 在Ubuntu22 10安装nvidia docker在执行以下命令时 distribution 61 etc os release echo ID VERSION ID amp am
  • 测试torch方法是否支持半精度

    并不是所有的torch方法都支持半精度计算 测试半精度计算需要在cuda上 xff0c cpu不支持半精度 因此首先需要创建半精度变量 xff0c 并放到cuda设备上 部分方法在低版本不支持 xff0c 在高版本支持半精度计算 xff0c
  • yolov5关闭wandb

    yolov5训练过程中wandb总是提示登入账号 xff0c 不登入还不能继续训练 xff0c 想要关闭wandb xff0c 直接不使用即可 在 yolov5 utils loggers wandb wandb utils py中 imp
  • 目标检测 YOLOv5的loss权重,以及与图像大小的关系

    1 目标检测 YOLOv5的loss权重 YOLOv5中有三个损失分别是 box obj cls 在超参数配置文件hyp yaml中可以设置基础值 xff0c 例如 box 0 05 cls 0 5 obj 1 训练使用时 xff0c 在t
  • 手写一个JSON反序列化程序

    上一篇文章 JSON是什么 给大家介绍了JSON的标准规范 xff0c 今天就自己动手写一个JSON的反序列化程序 xff0c 并命名它为 zjson 0 开始之前 本篇文章的目的是学习实践 xff0c 所以我们选择相对简单的Python实
  • yolov5源码解析--输出

    本文章基于yolov5 6 2版本 主要讲解的是yolov5是怎么在最终的特征图上得出物体边框 置信度 物体分类的 一 总体框架 首先贴出总体框架 xff0c 直接就拿官方文档的图了 xff0c 本文就是接着右侧的那三层输出开始讨论 Bac
  • yolov5源码解析--损失计算与anchor

    本文章基于yolov5 6 2版本 主要讲解的是yolov5在训练过程中是怎么由推理结果和标签来进行损失计算的 损失函数往往可以作为调优的一个切入点 xff0c 所以我们首先要了解它 一 代码入口 损失函数的调用点如下 xff0c 在tra
  • 多任务学习中各loss权重应该如何设计呢?

    来源 xff1a 22 封私信 80 条消息 多任务学习中各loss权重应该如何设计呢 xff1f 知乎 zhihu com 多损失在深度学习中很常见 xff0c 例如 xff1a 目标检测 xff1a 以 YOLO 为例 xff0c 它的
  • YOLOv5之autoanchor看这一篇就够了

    简单粗暴 xff0c 废话也不罗嗦了 xff0c 学习目的就是解决下面三个问题 xff0c 1 默认anchor t设置为4 xff0c 这个参数如何调整 xff1f 有没有必要调整 xff1f xff08 首先网上很多说这个参数是长宽比是
  • nvidia-smi报错:NVIDIA-SMI has failed because it couldn‘t communicate with the NVIDIA driver 原因及避坑解决方案

    由于断电 xff0c 服务器重启了 xff0c 当再次跑实验时 xff0c 发现cuda不可用 xff0c 于是输入 nvidia smi 才发现了一个错误 xff0c 如下 xff1a NVIDIA SMI has failed beca
  • nvidia-smi命令输出结果缓慢问题

    nvidia smi命令输出结果缓慢问题 xff0c 可能的原因和解决办法 xff1a 1 当前已经打开了节能模式 xff08 需要关闭节能模式 xff0c 切换到持久模式 xff09 如何关闭节能模式 xff1a 方法1 xff1a su
  • PL/SQL基础(1):语法

    本篇是 Oracle基础小结 系列之一 本篇目录 1 什么是PL SQL xff1f 2 PL SQL基本结构 3 PL SQL符号定义 4 PL SQL数据类型 5 PL SQL条件句法 6 PL SQL循环 什么是PL SQL xff1