Plsql 简明教程

PL/SQL - Constants and Literals

在本章中,我们将讨论 PL/SQL 中的 constantsliterals 。常量保存的值一旦声明,就不会在程序中更改。常量声明指定其名称、数据类型和值,并为其分配存储。声明还可以施加 NOT NULL constraint

In this chapter, we will discuss constants and literals in PL/SQL. A constant holds a value that once declared, does not change in the program. A constant declaration specifies its name, data type, and value, and allocates storage for it. The declaration can also impose the NOT NULL constraint.

Declaring a Constant

常量使用 CONSTANT 关键字声明。它需要一个初始值,并且不允许更改该值。例如 −

A constant is declared using the CONSTANT keyword. It requires an initial value and does not allow that value to be changed. For example −

PI CONSTANT NUMBER := 3.141592654;
DECLARE
   -- constant declaration
   pi constant number := 3.141592654;
   -- other declarations
   radius number(5,2);
   dia number(5,2);
   circumference number(7, 2);
   area number (10, 2);
BEGIN
   -- processing
   radius := 9.5;
   dia := radius * 2;
   circumference := 2.0 * pi * radius;
   area := pi * radius * radius;
   -- output
   dbms_output.put_line('Radius: ' || radius);
   dbms_output.put_line('Diameter: ' || dia);
   dbms_output.put_line('Circumference: ' || circumference);
   dbms_output.put_line('Area: ' || area);
END;
/

当以上代码在 SQL 提示符下执行时,它会生成以下结果:

When the above code is executed at the SQL prompt, it produces the following result −

Radius: 9.5
Diameter: 19
Circumference: 59.69
Area: 283.53

Pl/SQL procedure successfully completed.

The PL/SQL Literals

文字是一个明确的数字、字符、字符串或布尔值,而不是由标识符表示。例如,TRUE、786、NULL、'tutorialspoint' 都是布尔、数字或字符串类型的文字。在 PL/SQL 中,文字区分大小写。PL/SQL 支持以下类型的文字 −

A literal is an explicit numeric, character, string, or Boolean value not represented by an identifier. For example, TRUE, 786, NULL, 'tutorialspoint' are all literals of type Boolean, number, or string. PL/SQL, literals are case-sensitive. PL/SQL supports the following kinds of literals −

  1. Numeric Literals

  2. Character Literals

  3. String Literals

  4. BOOLEAN Literals

  5. Date and Time Literals

下表提供以上所有类文字值的示例。

The following table provides examples from all these categories of literal values.

S.No

Literal Type & Example

1

Numeric Literals 050 78 -14 0 +32767 6.6667 0.0 -12.0 3.14159 +7800.00 6E5 1.0E-8 3.14159e0 -1E38 -9.5e-3

2

Character Literals 'A' '%' '9' ' ' 'z' '('

3

String Literals 'Hello, world!' 'Tutorials Point' '19-NOV-12'

4

BOOLEAN Literals TRUE, FALSE, and NULL.

5

Date and Time Literals DATE '1978-12-25'; TIMESTAMP '2012-10-29 12:01:01';

要在字符串文字中嵌入单引号,请像以下程序所示将两个单引号并排放置 −

To embed single quotes within a string literal, place two single quotes next to each other as shown in the following program −

DECLARE
   message  varchar2(30):= 'That''s tutorialspoint.com!';
BEGIN
   dbms_output.put_line(message);
END;
/

当以上代码在 SQL 提示符下执行时,它会生成以下结果:

When the above code is executed at the SQL prompt, it produces the following result −

That's tutorialspoint.com!

PL/SQL procedure successfully completed.