T Sql 简明教程

T-SQL - Quick Guide

T-SQL - Overview

在 20 世纪 70 年代,IBM 开发了一种名为“SEQUEL”的结构化英语查询语言,后来 SEQUEL 被重新命名为“SQL”,即结构化查询语言。

In 1970’s the product called 'SEQUEL', structured English query language, developed by IBM and later SEQUEL was renamed to 'SQL' which stands for Structured Query Language.

1986 年,SQL 获得 ANSI(美国国家标准协会)的批准,1987 年,它获得 ISO(国际标准组织)的批准。

In 1986, SQL was approved by ANSI (American national Standards Institute) and in 1987, it was approved by ISO (International Standards Organization).

SQL 是一种结构化查询语言,是所有 RDBMS 产品的通用数据库语言。不同的 RDBMS 产品供应商为自己的 RDBMS 产品扩展了 SQL,开发了自己的数据库语言。

SQL is a structure query language which is a common database language for all RDBMS products. Different RDBMS product vendors have developed their own database language by extending SQL for their own RDBMS products.

T-SQL 代表事务结构查询语言,它是 Microsoft 产品,是 SQL 语言的扩展。

T-SQL stands for Transact Structure Query Language which is a Microsoft product and is an extension of SQL Language.

Example

MS SQL Server - SQL\T-SQL

ORACLE - SQL\PL-SQL

T-SQL - Data Types

SQL Server 数据类型是一种属性,它指定了任何对象的 data 类型。每列,变量和表达式在 SQL Server 中有相关的 data 类型。在创建表时可使用这些数据类型。你可针对你的需求为表格栏选择特定的数据类型。

SQL Server data type is an attribute that specifies types of data of any object. Each column, variable and expression has related data type in SQL Server. These data types can be used while creating tables. You can choose a particular data type for a table column based on your requirement.

SQL Server 提供了七个类别包括其他类别的 data 类型以供使用。

SQL Server offers seven categories including other category of data types for use.

Exact Numeric Types

Type

From

To

bigint

-9,223,372,036,854,775,808

9,223,372,036,854,775,807

int

-2,147,483,648

2,147,483,647

smallint

-32,768

32,767

tinyint

0

255

bit

0

1

decimal

-10^38 +1

10^38 –1

numeric

-10^38 +1

10^38 –1

money

-922,337,203,685,477.5808

+922,337,203,685,477.5807

smallmoney

-214,748.3648

+214,748.3647

数字和十进制是固定精度和刻度 data 类型,以及在功能上是相等的。

Numeric and decimal are Fixed precision and scale data types and are functionally equivalent.

Approximate Numeric Types

Type

From

To

Float

-1.79E + 308

1.79E + 308

Real

-3.40E + 38

3.40E + 38

Date and Time Types

Type

From

To

datetime(3.33 milliseconds accuracy)

Jan 1, 1753

Dec 31, 9999

smalldatetime(1 minute accuracy)

Jan 1, 1900

Jun 6, 2079

date(1 day accuracy. Introduced in SQL Server 2008)

Jan 1, 0001

Dec 31, 9999

datetimeoffset(100 nanoseconds accuracy. Introduced in SQL Server 2008)

Jan 1, 0001

Dec 31, 9999

datetime2(100 nanoseconds accuracy. Introduced in SQL Server 2008)

Jan 1, 0001

Dec 31, 9999

time(100 nanoseconds accuracy. Introduced in SQL Server 2008)

00:00:00.0000000

23:59:59.9999999

Character Strings

Sr.No

Type & Description

1

char Fixed-length non-Unicode character data with a maximum length of 8,000 characters.

2

varchar Variable-length non-Unicode data with a maximum of 8,000 characters.

3

Varchar (max) Variable-length non-Unicode data with a maximum length of 231 characters (Introduced in SQL Server 2005).

4

text Variable-length non-Unicode data with a maximum length of 2,147,483,647 characters

Unicode Character Strings

Sr.No

Type & Description

1

nchar Fixed-length Unicode data with a maximum length of 4,000 characters.

2

nvarchar Variable-length Unicode data with a maximum length of 4,000 characters.

3

Nvarchar (max) Variable-length Unicode data with a maximum length of 230 characters (Introduced in SQL Server 2005).

4

ntext Variable-length Unicode data with a maximum length of 1,073,741,823 characters.

Binary Strings

Sr.No

Type & Description

1

binary Fixed-length binary data with a maximum length of 8,000 bytes.

2

varbinary Variable-length binary data with a maximum length of 8,000 bytes.

3

varbinary(max) Variable-length binary data with a maximum length of 231 bytes (Introduced in SQL Server 2005).

4

image Variable-length binary data with a maximum length of 2,147,483,647 bytes.

Other Data Types

  1. sql_variant − Stores values of various SQL Server-supported data types, except text, ntext, and timestamp.

  2. timestamp − Stores a database-wide unique number that gets updated every time a row gets updated.

  3. uniqueidentifier − Stores a globally unique identifier (GUID).

  4. xml − Stores XML data. You can store XML instances in a column or a variable (Introduced in SQL Server 2005).

  5. cursor − A reference to a cursor.

  6. table − Stores a result set for later processing.

  7. hierarchyid − A variable length, system data type used to represent position in a hierarchy (Introduced in SQL Server 2008).

T-SQL - Create Tables

创建基本表涉及命名表并定义其列和每个列的数据类型。

Creating a basic table involves naming the table and defining its columns and each column’s data type.

SQL Server CREATE TABLE 语句用于创建新表。

The SQL Server CREATE TABLE statement is used to create a new table.

Syntax

以下是 CREATE TABLE 语句的基本语法:

Following is the basic syntax of CREATE TABLE statement −

CREATE TABLE table_name(
   column1 datatype,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
   PRIMARY KEY( one or more columns ));

CREATE TABLE 是告诉数据库系统你想要做什么的关键字。在本例中,你要创建一个新表。表中唯一名称或标识符应位于 CREATE TABLE 语句后面。然后括号中应该是定义表中每一列的内容及其是什么数据类型的列表。通过以下示例可以更清楚地了解语法。

CREATE TABLE is the keyword telling the database system what you want to do. In this case, you want to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement. Then in brackets comes the list defining each column in the table and what sort of data type it is. The syntax becomes clearer to understand with the following example.

可以使用 CREATE TABLE 语句与 SELECT 语句的组合来创建现有表的副本。你可以在使用其他表创建表中查看所有详细信息。

A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. You can check complete details at Create Table Using another Table.

Example

在本示例中,让我们创建一个以 ID 为主键且 NOT NULL 的 CUSTOMERS 表,约束表明在该表中创建记录时,这些字段不能为 NULL:

In this example, let’s create a CUSTOMERS table with ID as primary key and NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table −

CREATE TABLE CUSTOMERS(
   ID   INT              NOT NULL,
   NAME VARCHAR (20)     NOT NULL,
   AGE  INT              NOT NULL,
   ADDRESS  CHAR (25) ,
   SALARY   DECIMAL (18, 2),
   PRIMARY KEY (ID));

你可以通过查看 SQL Server 显示的消息来验证你的表是否已成功创建,此外还可以使用以下命令:

You can verify if your table has been created successfully by looking at the message displayed by the SQL server, otherwise you can use the following command −

exec sp_columns CUSTOMERS

以上命令会产生以下输出。

The above command produces the following output.

TABLE_QUALIFIER   TABLE_OWNER   TABLE_NAME   COLUMN_NAME   DATA_TYPE   TYPE_NAME
   PRECISION   LENGTH SCALE   RADIX   NULLABLE   REMARKS   COLUMN_DEF   SQL_DATA_TYPE
   SQL_DATETIME_SUB   CHAR_OCTET_LENGTH   ORDINAL_POSITION   IS_NULLABLE   SS_DATA_TYPE

TestDB    dbo    CUSTOMERS   ID        4    int      10   4    0      10     0
   NULL   NULL   4   NULL    NULL      1    NO       56

TestDB    dbo    CUSTOMERS   NAME      12   varchar  20   20   NULL   NULL   0
   NULL   NULL   12   NULL   20        2    NO       39

TestDB    dbo    CUSTOMERS   AGE       4    int      10   4    0      10     0
   NULL   NULL   4   NULL    NULL      3    NO       56

TestDB    dbo    CUSTOMERS   ADDRESS   1    char     25   25   NULL   NULL   1
   NULL   NULL   1   NULL    25   4    YES  39

TestDB    dbo    CUSTOMERS   SALARY    3    decimal  18   20   2      10     1
   NULL   NULL   3   NULL    NULL      5    YES      106

你现在可以看见 CUSTOMERS 表已在你的数据库中可用,你可以使用它来存储与客户相关的所需信息。

You can now see that CUSTOMERS table is available in your database which you can use to store required information related to customers.

T-SQL - Drop Tables

SQL Server DROP TABLE 语句用于删除表定义以及表的所有数据、索引、触发器、约束和权限规范。

The SQL Server DROP TABLE statement is used to remove a table definition and all data, indexes, triggers, constraints, and permission specifications for that table.

Note − 使用此命令时必须小心,因为一旦表被删除,表中提供的所有信息也将永远丢失。

Note − You have to be careful while using this command because once a table is deleted then all the information available in the table would also be lost forever.

Syntax

以下是 DROP TABLE 语句的基本语法 −

Following is the basic syntax of DROP TABLE statement −

DROP TABLE table_name;

Example

让我们先验证 CUSTOMERS 表,然后从数据库中删除它 −

Let us first verify CUSTOMERS table and then we will delete it from the database −

Exec sp_columns CUSTOMERS;

以上命令显示了以下表。

The above command shows the following table.

TABLE_QUALIFIER   TABLE_OWNER   TABLE_NAME   COLUMN_NAME   DATA_TYPE   TYPE_NAME
   PRECISION   LENGTH SCALE   RADIX   NULLABLE   REMARKS   COLUMN_DEF   SQL_DATA_TYPE
   SQL_DATETIME_SUB   CHAR_OCTET_LENGTH   ORDINAL_POSITION   IS_NULLABLE   SS_DATA_TYPE

TestDB    dbo    CUSTOMERS   ID        4   int        10   4    0      10     0
   NULL   NULL   4   NULL    NULL      1   NO         56

TestDB    dbo    CUSTOMERS   NAME      12  varchar    20   20   NULL   NULL   0
   NULL   NULL   12   NULL   20        2   NO         39

TestDB    dbo    CUSTOMERS   AGE       4   int        10   4    0      10     0
   NULL   NULL   4   NULL    NULL      3   NO         56

TestDB    dbo    CUSTOMERS   ADDRESS   1   char       25   25   NULL   NULL   1
   NULL   NULL   1   NULL    25        4   YES        39

TestDB    dbo    CUSTOMERS   SALARY   3   decimal     18   20   2      10     1
   NULL   NULL   3   NULL    NULL     5   YES         106

CUSTOMERS 表在数据库中可用,因此让我们删除它。以下是相同的命令。

CUSTOMERS table is available in the database, so let us drop it. Following is the command for the same.

DROP TABLE CUSTOMERS;
Command(s) completed successfully.

使用以上命令,你将不会得到任何行。

With the above command, you will not get any rows.

Exec sp_columns CUSTOMERS;
No rows\data will be displayed

T-SQL - INSERT Statement

SQL Server INSERT INTO 语句用于在数据库中的表中添加新数据行。

The SQL Server INSERT INTO statement is used to add new rows of data to a table in the database.

Syntax

以下是 INSERT INTO 语句的两个基本语法:

Following are the two basic syntaxes of INSERT INTO statement.

INSERT INTO TABLE_NAME [(column1, column2, column3,...columnN)]
VALUES (value1, value2, value3,...valueN);

其中,column1、column2、……​columnN 是要在其中插入数据的表中的列名。

Where column1, column2,…​columnN are the names of the columns in the table into which you want to insert data.

如果你为表的所有列添加值,则不需要在 SQL 查询中指定列名。但确保值的顺序与表中的列相同。以下是 SQL INSERT INTO 语法 −

You need not specify the column(s) name in the SQL query if you are adding values for all the columns of the table. But make sure the order of the values is in the same order as the columns in the table. Following is the SQL INSERT INTO syntax −

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

Example

以下语句将在 CUSTOMERS 表中创建六条记录 −

Following statements will create six records in CUSTOMERS table −

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Komal', 22, 'MP', 4500.00 );

Syntax

你可以使用第二个语法在 CUSTOMERS 表中创建记录,如下所示 −

You can create a record in CUSTOMERS table using second syntax as follows −

INSERT INTO CUSTOMERS VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );

上面的所有语句都将在 CUSTOMERS 表中生成以下记录−

All the above statements will produce the following records in CUSTOMERS table −

ID  NAME       AGE         ADDRESS              SALARY
1   Ramesh     32          Ahmedabad            2000.00
2   Khilan     25          Delhi                1500.00
3   kaushik    23          Kota                 2000.00
4   Chaitali   25          Mumbai               6500.00
5   Hardik     27          Bhopal               8500.00
6   Komal      22          MP                   4500.00
7   Muffy      24          Indore               10000.00

Populate One Table Using Another Table

您可以通过在另一张表上 SELECT 语句来填充表中的数据,前提是另一张表有一组字段,需要先填充第一张表。以下是语法−

You can populate data into a table through SELECT statement over another table provided another table has a set of fields, which are required to populate first table. Following is the syntax −

INSERT INTO first_table_name
   SELECT column1, column2, ...columnN
      FROM second_table_name
      [WHERE condition];

T-SQL - SELECT Statement

SQL Server SELECT 语句用于从数据库表中获取数据,这些数据以结果表格的形式返回。这些结果表格被称为 result-sets

SQL Server SELECT statement is used to fetch the data from a database table which returns data in the form of result table. These result tables are called result-sets.

Syntax

以下是 SELECT 语句的基本语法 −

Following is the basic syntax of SELECT statement −

SELECT column1, column2, columnN FROM table_name;

其中,列 1、列 2…​ 是您要获取其值的表的字段。如果您想获取字段中提供的所有字段,则可以使用以下语法 −

Where, column1, column2…​are the fields of a table whose values you want to fetch. If you want to fetch all the fields available in the field, then you can use the following syntax −

SELECT * FROM table_name;

Example

考虑包含以下记录的 CUSTOMERS 表:

Consider the CUSTOMERS table having the following records −

ID  NAME       AGE       ADDRESS             SALARY
1   Ramesh     32        Ahmedabad           2000.00
2   Khilan     25        Delhi               1500.00
3   kaushik    23        Kota                2000.00
4   Chaitali   25        Mumbai              6500.00
5   Hardik     27        Bhopal              8500.00
6   Komal      22        MP                  4500.00
7   Muffy      24        Indore              10000.00

以下命令是一个示例,它将获取 CUSTOMERS 表中提供的客户的 ID、姓名和工资字段 −

Following command is an example, which would fetch ID, Name and Salary fields of the customers available in CUSTOMERS table −

SELECT ID, NAME, SALARY FROM CUSTOMERS;

以上命令将生成以下输出。

The above command will produce the following output.

ID  NAME          SALARY
1   Ramesh        2000.00
2   Khilan        1500.00
3   kaushik       2000.00
4   Chaitali      6500.00
5   Hardik        8500.00
6   Komal         4500.00
7   Muffy         10000.00

如果你想提取 CUSTOMERS 表的所有字段,那么使用以下查询 −

If you want to fetch all the fields of CUSTOMERS table, then use the following query −

SELECT * FROM CUSTOMERS;

上述代码将产生以下输出。

The above will produce the following output.

ID  NAME       AGE       ADDRESS              SALARY
1   Ramesh     32        Ahmedabad            2000.00
2   Khilan     25        Delhi                1500.00
3   kaushik    23        Kota                 2000.00
4   Chaitali   25        Mumbai               6500.00
5   Hardik     27        Bhopal               8500.00
6   Komal      22        MP                   4500.00
7   Muffy      24        Indore               10000.00

T-SQL - UPDATE Statement

SQL Server UPDATE 查询用于修改表中现有的记录。

The SQL Server UPDATE Query is used to modify the existing records in a table.

可以将 WHERE 子句与 UPDATE 查询结合使用以更新所选行,否则会影响所有行。

You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows would be affected.

Syntax

以下是带 WHERE 子句的 UPDATE 查询的基本语法:

Following is the basic syntax of UPDATE query with WHERE clause −

UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

可以使用 AND 或 OR 运算符组合 N 个条件。

You can combine N number of conditions using AND or OR operators.

Example

考虑包含以下记录的 CUSTOMERS 表:

Consider the CUSTOMERS table having the following records −

ID  NAME       AGE       ADDRESS             SALARY
1   Ramesh     32        Ahmedabad           2000.00
2   Khilan     25        Delhi               1500.00
3   kaushik    23        Kota                2000.00
4   Chaitali   25        Mumbai              6500.00
5   Hardik     27        Bhopal              8500.00
6   Komal      22        MP                  4500.00
7   Muffy      24        Indore              10000.00

以下命令是一个示例,用于更新 ID 为 6 的客户地址:

Following command is an example, which would update ADDRESS for a customer whose ID is 6 −

UPDATE CUSTOMERS
SET ADDRESS = 'Pune'
WHERE ID = 6;

客户表现在将具有以下记录:

CUSTOMERS table will now have the following records −

ID  NAME       AGE       ADDRESS             SALARY
1   Ramesh     32        Ahmedabad           2000.00
2   Khilan     25        Delhi               1500.00
3   kaushik    23        Kota                2000.00
4   Chaitali   25        Mumbai              6500.00
5   Hardik     27        Bhopal              8500.00
6   Komal      22        Pune                4500.00
7   Muffy      24        Indore              10000.00

如果要修改 CUSTOMERS 表中的所有 ADDRESS 和 SALARY 列值,则不需要使用 WHERE 子句。UPDATE 查询如下:

If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you do not need to use WHERE clause. UPDATE query would be as follows −

UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;

CUSTOMERS 表现在将具有以下记录。

CUSTOMERS table will now have the following records.

ID  NAME       AGE       ADDRESS          SALARY
1   Ramesh     32        Pune             1000.00
2   Khilan     25        Pune             1000.00
3   kaushik    23        Pune             1000.00
4   Chaitali   25        Pune             1000.00
5   Hardik     27        Pune             1000.00
6   Komal      22        Pune             1000.00
7   Muffy      24        Pune             1000.00

T-SQL - DELETE Statement

SQL Server DELETE 查询用于从表中删除现有记录。

The SQL Server DELETE Query is used to delete the existing records from a table.

您必须将 WHERE 子句与 DELETE 查询一起使用以删除选定的行,否则将删除所有记录。

You have to use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be deleted.

Syntax

以下是有 WHERE 子句的 DELETE 查询的基本语法 −

Following is the basic syntax of DELETE query with WHERE clause −

DELETE FROM table_name
WHERE [condition];

可以使用 AND 或 OR 运算符组合 N 个条件。

You can combine N number of conditions using AND or OR operators.

Example

考虑包含以下记录的 CUSTOMERS 表:

Consider the CUSTOMERS table having the following records −

ID  NAME       AGE       ADDRESS            SALARY
1   Ramesh     32        Ahmedabad          2000.00
2   Khilan     25        Delhi              1500.00
3   kaushik    23        Kota               2000.00
4   Chaitali   25        Mumbai             6500.00
5   Hardik     27        Bhopal             8500.00
6   Komal      22        MP                 4500.00
7   Muffy      24        Indore             10000.00

以下命令是一个示例,它将 DELETE 一个 ID 为 6 的客户 −

Following command is an example, which would DELETE a customer, whose ID is 6 −

DELETE FROM CUSTOMERS
WHERE ID = 6;

CUSTOMERS 表现在将具有以下记录。

CUSTOMERS table will now have the following records.

ID  NAME       AGE       ADDRESS              SALARY
1   Ramesh     32        Ahmedabad            2000.00
2   Khilan     25        Delhi                1500.00
3   kaushik    23        Kota                 2000.00
4   Chaitali   25        Mumbai               6500.00
5   Hardik     27        Bhopal               8500.00
7   Muffy      24        Indore               10000.00

如果你想从 CUSTOMERS 表中删除所有记录,你不需要使用 WHERE 子句。DELETE 查询将如下所示 −

If you want to DELETE all the records from CUSTOMERS table, you do not need to use WHERE clause. DELETE query would be as follows −

DELETE FROM CUSTOMERS;

CUSTOMERS 表现在没有任何记录。

CUSTOMERS table now will not have any record.

T-SQL - WHERE Clause

MS SQL Server WHERE 子句用于在从单个表获取数据或与多个表连接时指定条件。

The MS SQL Server WHERE clause is used to specify a condition while fetching the data from single table or joining with multiple tables.

如果满足给定条件,则它仅从表中返回一个特定值。您将必须使用 WHERE 子句来筛选记录并仅获取必需的记录。

If the given condition is satisfied, only then it returns a specific value from the table. You will have to use WHERE clause to filter the records and fetch only necessary records.

WHERE 子句不仅用于 SELECT 语句中,而且还用于 UPDATE、DELETE 语句中,我们将在后续章节中研究这些语句。

The WHERE clause is not only used in SELECT statement, but it is also used in UPDATE, DELETE statement, etc., which we would examine in subsequent chapters.

Syntax

以下是带有 WHERE 子句的 SELECT 语句的基本语法−

Following is the basic syntax of SELECT statement with WHERE clause −

SELECT column1, column2, columnN
FROM table_name
WHERE [condition]

您可以使用 >、<、=、LIKE、NOT 等比较或逻辑运算符指定条件。以下示例将阐明此概念。

You can specify a condition using comparison or logical operators like >, <, =, LIKE, NOT, etc. The following example will make this concept clear.

Example

考虑包含以下记录的 CUSTOMERS 表:

Consider the CUSTOMERS table having the following records −

ID  NAME       AGE       ADDRESS            SALARY
1   Ramesh     32        Ahmedabad          2000.00
2   Khilan     25        Delhi              1500.00
3   kaushik    23        Kota               2000.00
4   Chaitali   25        Mumbai             6500.00
5   Hardik     27        Bhopal             8500.00
6   Komal      22        MP                 4500.00
7   Muffy      24        Indore             10000.00

以下命令是一个示例,它将从 CUSTOMERS 表中获取 ID、Name 和 Salary 字段,其中工资大于 2000。

Following command is an example which would fetch ID, Name and Salary fields from the CUSTOMERS table where salary is greater than 2000.

SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE SALARY > 2000;

以上命令将生成以下输出。

The above command will produce the following output.

ID  NAME       SALARY
4   Chaitali   6500.00
5   Hardik     8500.00
6   Komal      4500.00
7   Muffy      10000.00

以下命令是一个示例,它将为名为“Hardik”的客户从 CUSTOMERS 表中获取 ID、Name 和 Salary 字段。需要注意的是,所有字符串都应放在单引号('')内,而数字值应不带任何引号,如上例所示−

Following command is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS table for a customer with the name ‘Hardik’. It is important to note that all the strings should be given inside single quotes ('') whereas numeric values should be given without any quote as in the above example −

SELECT ID, NAME, SALARY
FROM CUSTOMERS
WHERE NAME = 'Hardik';

以上命令将生成以下输出。

The above command will produce the following output.

ID  NAME     SALARY
5   Hardik   8500.00

T-SQL - LIKE Clause

MS SQL Server LIKE 子句用于使用通配符运算符将值与类似值进行比较。与 LIKE 运算符结合使用的通配符有两种 -

The MS SQL Server LIKE clause is used to compare a value to similar values using wildcard operators. There are two wildcards used in conjunction with the LIKE operator −

  1. The percent sign (%)

  2. The underscore (_)

百分号表示零个、一个或多个字符。下划线表示单个数字或字符。这些符号可以组合使用。

The percent sign represents zero, one, or multiple characters. The underscore represents a single number or character. The symbols can be used in combinations.

Syntax

以下是 % 和 _ 的基本语法。

Following is the basic syntax of % and _.

SELECT *\column-list FROM table_name
WHERE column LIKE 'XXXX%'

or

SELECT *\column-list FROM table_name
WHERE column LIKE '%XXXX%'

or

SELECT *\column-list FROM table_name
WHERE column LIKE 'XXXX_'

or

SELECT *\column-list FROM table_name
WHERE column LIKE '_XXXX'

or

SELECT  *\column-list FROM table_name
WHERE column LIKE '_XXXX_'

您可以使用 AND 或 OR 运算符组合 N 个条件。XXXX 可以是任何数字或字符串值。

You can combine N number of conditions using AND or OR operators. XXXX could be any numeric or string value.

Example

以下是一些示例,显示 WHERE 部分具有带 '%' 和 '_' 运算符的不同 LIKE 子句。

Following are a number of examples showing WHERE part having different LIKE clause with '%' and '_' operators.

Sr.No

Statement & Description

1

WHERE SALARY LIKE '200%' Finds any values that start with 200

2

WHERE SALARY LIKE '%200%' Finds any values that have 200 in any position

3

WHERE SALARY LIKE '_00%' Finds any values that have 00 in the second and third positions

4

WHERE SALARY LIKE '2_%_%' Finds any values that start with 2 and are at least 3 characters in length

5

WHERE SALARY LIKE '%2' Finds any values that end with 2

6

WHERE SALARY LIKE '_2%3' Finds any values that have a 2 in the second position and end with a 3

7

WHERE SALARY LIKE '2___3' Finds any values in a five-digit number that start with 2 and end with 3

可以将 CUSTOMERS 表视为包含以下记录。

Consider the CUSTOMERS table having the following records.

ID  NAME       AGE       ADDRESS            SALARY
1   Ramesh     32        Ahmedabad          2000.00
2   Khilan     25        Delhi              1500.00
3   kaushik    23        Kota               2000.00
4   Chaitali   25        Mumbai             6500.00
5   Hardik     27        Bhopal             8500.00
6   Komal      22        MP                 4500.00
7   Muffy      24        Indore             10000.00

以下命令是一个示例,它会显示 CUSTOMERS 表中 SALARY 以 200 开头的所有记录。

Following command is an example, which will display all the records from CUSTOMERS table where SALARY starts with 200.

SELECT * FROM CUSTOMERS
WHERE SALARY LIKE '200%';

以上命令将生成以下输出。

The above command will produce the following output.

ID   NAME     AGE     ADDRESS       SALARY
1    Ramesh   32      Ahmedabad     2000.00
3    kaushik  23      Kota          2000.00

T-SQL - ORDER BY Clause

MS SQL Server ORDER BY 子句用于按一个或多个列基于升序或降序对数据进行排序。默认情况下,一些数据库按升序对查询结果进行排序。

The MS SQL Server ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sort query results in ascending order by default.

Syntax

以下是 ORDER BY 子句的基本语法。

Following is the basic syntax of ORDER BY clause.

SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

你可以在 ORDER BY 子句中使用多个列。确保要用于排序的列在列列表中。

You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be in column-list.

Example

考虑包含以下记录的 CUSTOMERS 表:

Consider the CUSTOMERS table having the following records −

ID  NAME       AGE       ADDRESS            SALARY
1   Ramesh     32        Ahmedabad          2000.00
2   Khilan     25        Delhi              1500.00
3   kaushik    23        Kota               2000.00
4   Chaitali   25        Mumbai             6500.00
5   Hardik     27        Bhopal             8500.00
6   Komal      22        MP                 4500.00
7   Muffy      24        Indore             10000.00

以下命令是一个示例,按 NAME 和 SALARY 升序对结果进行排序。

Following command is an example, which would sort the result in ascending order by NAME and SALARY.

SELECT * FROM CUSTOMERS
   ORDER BY NAME, SALARY

以上命令将生成以下输出。

The above command will produce the following output.

ID  NAME       AGE       ADDRESS           SALARY
4   Chaitali   25        Mumbai            6500.00
5   Hardik     27        Bhopal            8500.00
3   kaushik    23        Kota              2000.00
2   Khilan     25        Delhi             1500.00
6   Komal      22        MP                4500.00
7   Muffy      24        Indore            10000.00
1   Ramesh     32        Ahmedabad         2000.00

以下命令是一个示例,按 NAME 降序对结果进行排序。

Following command is an example, which would sort the result in descending order by NAME.

SELECT * FROM CUSTOMERS
   ORDER BY NAME DESC

以上命令将生成以下结果 −

The above command will produce the following result −

ID  NAME       AGE       ADDRESS            SALARY
1   Ramesh     32        Ahmedabad          2000.00
7   Muffy      24        Indore             10000.00
6   Komal      22        MP                 4500.00
2   Khilan     25        Delhi              1500.00
3   kaushik    23        Kota               2000.00
5   Hardik     27        Bhopal             8500.00
4   Chaitali   25        Mumbai             6500.00

T-SQL - GROUP BY Clause

SQL Server GROUP BY 子句与 SELECT 语句配合使用,将相同数据整理到组中。

The SQL Server GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.

GROUP BY 子句在 SELECT 语句中紧跟在 WHERE 子句之后,并且出现在 ORDER BY 子句之前。

The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.

Syntax

以下是 GROUP BY 子句的基本语法。GROUP BY 子句必须跟在 WHERE 子句的条件之后,如果使用,则必须在 ORDER BY 子句之前。

Following is the basic syntax of GROUP BY clause. The GROUP BY clause must follow the conditions in the WHERE clause and must precede the ORDER BY clause if one is used.

SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

Example

考虑 CUSTOMERS 表具有以下记录 −

Consider the CUSTOMERS table is having the following records −

ID  NAME       AGE       ADDRESS          SALARY
1   Ramesh     32        Ahmedabad        2000.00
2   Khilan     25        Delhi            1500.00
3   kaushik    23        Kota             2000.00
4   Chaitali   25        Mumbai           6500.00
5   Hardik     27        Bhopal           8500.00
6   Komal      22        MP               4500.00
7   Muffy      24        Indore           10000.00

如果您想了解每个客户的工资总额,那么以下将是 GROUP BY 查询。

If you want to know the total amount of salary on each customer, then following will be the GROUP BY query.

SELECT NAME, SUM(SALARY) as [sum of salary] FROM CUSTOMERS
   GROUP BY NAME;

以上命令将生成以下输出。

The above command will produce the following output.

NAME        sum of salary
Chaitali    6500.00
Hardik      8500.00
kaushik     2000.00
Khilan      1500.00
Komal       4500.00
Muffy       10000.00
Ramesh      2000.00

现在让我们考虑以下 CUSTOMERS 表,其中有以下记录,带有重复姓名。

Let us now consider the following CUSTOMERS table having the following records with duplicate names.

ID  NAME       AGE       ADDRESS           SALARY
1   Ramesh     32        Ahmedabad         2000.00
2   Khilan     25        Delhi             1500.00
3   kaushik    23        Kota              2000.00
4   Chaitali   25        Mumbai            6500.00
5   Hardik     27        Bhopal            8500.00
6   Komal      22        MP                4500.00
7   Muffy      24        Indore            10000.00

如果您想了解每个客户的工资总额,那么以下将是 GROUP BY 查询。

If we want to know the total amount of salary on each customer, then following will be GROUP BY query.

SELECT NAME, SUM(SALARY) as [sum of salary] FROM CUSTOMERS
   GROUP BY NAME

以上命令将生成以下输出。

The above command will produce the following output.

NAME        sum of salary
Hardik      8500.00
kaushik     8500.00
Komal       4500.00
Muffy       10000.00
Ramesh      3500.00

T-SQL - DISTINCT Clause

MS SQL Server DISTINCT 关键字与 SELECT 语句一起使用,以消除所有重复的记录并仅获取唯一的记录。

The MS SQL Server DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only unique records.

在表中,你可能会遇到重复记录的情况。在获取这些记录时,只获取唯一记录比获取重复记录更有意义。

There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records.

Syntax

以下是 DISTINCT 关键字消除重复记录的基本语法。

Following is the basic syntax of DISTINCT keyword to eliminate duplicate records.

SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]

Example

可以将 CUSTOMERS 表视为包含以下记录。

Consider the CUSTOMERS table having the following records.

ID  NAME       AGE       ADDRESS            SALARY
1   Ramesh     32        Ahmedabad          2000.00
2   Khilan     25        Delhi              1500.00
3   kaushik    23        Kota               2000.00
4   Chaitali   25        Mumbai             6500.00
5   Hardik     27        Bhopal             8500.00
6   Komal      22        MP                 4500.00
7   Muffy      24        Indore             10000.00

让我们看看 다음 SELECT 查询如何返回重复的薪资记录。

Let us see how the following SELECT query returns duplicate salary records.

SELECT SALARY FROM CUSTOMERS
   ORDER BY SALARY

上述命令将产生以下输出,其中薪资 2000 出现两次,这是原始表中的重复记录。

The above command will produce the following output where salary 2000 comes twice which is a duplicate record from the original table.

SALARY
1500.00
2000.00
2000.00
4500.00
6500.00
8500.00
10000.00

现在,让我们对上述 SELECT 查询使用 DISTINCT 关键字并查看结果。

Let us now use DISTINCT keyword with the above SELECT query and see the result.

SELECT DISTINCT SALARY FROM CUSTOMERS
   ORDER BY SALARY

上述命令会产生以下输出,其中我们没有任何重复项。

The above command produces the following output where we do not have any duplicate entry.

SALARY
1500.00
2000.00
4500.00
6500.00
8500.00
10000.00

T-SQL - Joining Tables

MS SQL Server Joins 子句用于合并数据库中两个或更多表中的记录。JOIN 是通过使用每张表都通用的值来合并两张表中的字段的方法。

The MS SQL Server Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each.

考虑以下两个表,(a)CUSTOMERS 表如下−

Consider the following two tables, (a) CUSTOMERS table is as follows −

ID  NAME       AGE       ADDRESS             SALARY
1   Ramesh     32        Ahmedabad           2000.00
2   Khilan     25        Delhi               1500.00
3   kaushik    23        Kota                2000.00
4   Chaitali   25        Mumbai              6500.00
5   Hardik     27        Bhopal              8500.00
6   Komal      22        MP                  4500.00
7   Muffy      24        Indore              10000.00

(b)另一张表 ORDERS 如下−

(b) Another table is ORDERS as follows −

OID  DATE                       CUSTOMER_ID        AMOUNT
100  2009-10-08 00:00:00.000    3                  1500.00
101  2009-11-20 00:00:00.000    2                  1560.00
102  2009-10-08 00:00:00.000    3                  3000.00
103  2008-05-20 00:00:00.000    4                  2060.00

让我们在我们的 SELECT 语句中连接这两个表,如下所示 −

Let us join these two tables in our SELECT statement as follows −

SELECT ID, NAME, AGE, AMOUNT
   FROM CUSTOMERS, ORDERS
   WHERE  CUSTOMERS.ID = ORDERS.CUSTOMER_ID
OR
SELECT A.ID, A.NAME, A.AGE, B.AMOUNT
   FROM CUSTOMERS A inner join  ORDERS B on A.ID = B.Customer_ID

以上命令将生成以下输出。

The above command will produce the following output.

ID   NAME      AGE    AMOUNT
2    Khilan    25     1560.00
3    kaushik   23     1500.00
3    kaushik   23     3000.00
4    Chaitali  25     2060.00

需要注意的是,联接是在 WHERE 子句中执行的。可以使用多个运算符来联接表,例如 =、<、>、<>、⇐、>=、!=、BETWEEN、LIKE 和 NOT;它们都可以用于联接表。但是,最常见的运算符是等号。

It is noticeable that the join is performed in the WHERE clause. Several operators can be used to join tables, such as =, <, >, <>, ⇐, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables. However, the most common operator is the equal symbol.

MS SQL Server 联接类型−

MS SQL Server Join Types −

MS SQL Server 中有多种类型的联接可用 −

There are different types of joins available in MS SQL Server −

  1. INNER JOIN − Returns rows when there is a match in both tables.

  2. LEFT JOIN − Returns all rows from the left table, even if there are no matches in the right table.

  3. RIGHT JOIN − Returns all rows from the right table, even if there are no matches in the left table.

  4. FULL JOIN − Returns rows when there is a match in one of the tables.

  5. SELF JOIN − This is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the MS SQL Server statement.

  6. CARTESIAN JOIN − Returns the Cartesian product of the sets of records from the two or more joined tables.

T-SQL - Sub-Queries

sub-queryInner queryNested query 是另一个 SQL Server 查询内的一个查询,并且嵌入在 WHERE 子句中。子查询用于返回将用作主查询中一个条件的数据,以便进一步限制要检索的数据。

A sub-query or Inner query or Nested query is a query within another SQL Server query and embedded within the WHERE clause. A sub query is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.

子查询可与 SELECT、INSERT、UPDATE 和 DELETE 语句以及 =、<、>、>=、⇐、IN、BETWEEN 等运算符搭配使用。

Sub queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, ⇐, IN, BETWEEN, etc.

子查询必须遵循一些规则:

There are a few rules that sub queries must follow −

  1. You must enclose a subquery in parenthesis.

  2. A subquery must include a SELECT clause and a FROM clause.

  3. A subquery can include optional WHERE, GROUP BY, and HAVING clauses.

  4. A subquery cannot include COMPUTE or FOR BROWSE clauses.

  5. You can include an ORDER BY clause only when a TOP clause is included.

  6. You can nest sub queries up to 32 levels.

Subqueries with SELECT Statement

Syntax

子查询最常与 SELECT 语句一起使用。以下是基本语法。

Subqueries are most frequently used with the SELECT statement. Following is the basic syntax.

SELECT column_name [, column_name ]
FROM   table1 [, table2 ]
WHERE  column_name OPERATOR
   (SELECT column_name [, column_name ]
   FROM table1 [, table2 ]
   [WHERE])

Example

可以将 CUSTOMERS 表视为包含以下记录。

Consider the CUSTOMERS table having the following records.

ID  NAME       AGE       ADDRESS            SALARY
1   Ramesh     32        Ahmedabad          2000.00
2   Khilan     25        Delhi              1500.00
3   kaushik    23        Kota               2000.00
4   Chaitali   25        Mumbai             6500.00
5   Hardik     27        Bhopal             8500.00
6   Komal      22        MP                 4500.00
7   Muffy      24        Indore             10000.00

让我们对 SELECT 语句应用以下子查询。

Let us apply the following subquery with SELECT statement.

SELECT *
   FROM CUSTOMERS
   WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500)

以上命令将生成以下输出。

The above command will produce the following output.

ID  NAME       AGE       ADDRESS          SALARY
4   Chaitali   25        Mumbai           6500.00
5   Hardik     27        Bhopal           8500.00
7   Muffy      24        Indore           10000.00

Subqueries with INSERT Statement

子查询还可以与 INSERT 语句一起使用。INSERT 语句使用从子查询返回的数据插入另一个表。子查询中所选的数据可以使用任何字符、日期或数字函数进行修改。

Sub queries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date, or number functions.

Syntax

以下是基本语法。

Following is the basic syntax.

INSERT INTO table_name [ (column1 [, column2 ]) ]
   SELECT [ *|column1 [, column2 ]
   FROM table1 [, table2 ]
   [ WHERE VALUE OPERATOR ]

Example

考虑一个结构与 CUSTOMERS 表相似的表 CUSTOMERS_BKP。以下是可以将完整的 CUSTOMERS 表复制到 CUSTOMERS_BKP 的语法。

Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Following is the syntax to copy complete CUSTOMERS table into CUSTOMERS_BKP.

INSERT INTO CUSTOMERS_BKP
   SELECT * FROM CUSTOMERS
   WHERE ID IN (SELECT ID FROM CUSTOMERS)

Subqueries with UPDATE Statement

子查询可以与 UPDATE 语句联合使用。在使用 UPDATE 语句与子查询时,可以更新表中的单个或多个列。

The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement.

Syntax

以下是基本语法。

Following is the basic syntax.

UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
   (SELECT COLUMN_NAME
   FROM TABLE_NAME)
   [ WHERE) ]

Example

我们假设我们有可用的是 CUSTOMERS_BKP 表,它是 CUSTOMERS 表的备份。

Let us assume we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.

以下命令示例将对 CUSTOMERS 表中所有年龄大于或等于 27 的客户更新 SALARY,更新幅度为 0.25 倍。

Following command example updates SALARY by 0.25 times in CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.

UPDATE CUSTOMERS
   SET SALARY = SALARY * 0.25
   WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 )

这将影响两行,并且最终 CUSTOMERS 表将拥有以下记录。

This will impact two rows and finally CUSTOMERS table will have the following records.

ID  NAME       AGE       ADDRESS             SALARY
1   Ramesh     32        Ahmedabad           500.00
2   Khilan     25        Delhi               1500.00
3   kaushik    23        Kota                2000.00
4   Chaitali   25        Mumbai              6500.00
5   Hardik     27        Bhopal              2125.00
6   Komal      22        MP                  4500.00
7   Muffy      24        Indore              10000.00

Subqueries with DELETE Statement

与上面提到的其他任何语句一样,子查询可与 DELETE 语句一起使用。

The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above.

Syntax

以下是基本语法。

Following is the basic syntax.

DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
   (SELECT COLUMN_NAME
   FROM TABLE_NAME)
   [ WHERE) ]

Example

我们假设我们有可用的是 CUSTOMERS_BKP 表,它是 CUSTOMERS 表的备份。

Let us assume we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table.

以下命令示例将删除 CUSTOMERS 表中所有年龄大于或等于 27 的客户的记录。

Following command example deletes records from CUSTOMERS table for all the customers whose AGE is greater than or equal to 27.

DELETE FROM CUSTOMERS
   WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >=27 )

这将影响两行,并且最终 CUSTOMERS 表将拥有以下记录。

This would impact two rows and finally CUSTOMERS table will have the following records.

ID  NAME       AGE       ADDRESS          SALARY
2   Khilan     25        Delhi            1500.00
3   kaushik    23        Kota             2000.00
4   Chaitali   25        Mumbai           6500.00
6   Komal      22        MP               4500.00
7   Muffy      24        Indore           10000.00

T-SQL - Stored Procedures

MS SQL Server Stored procedure 可用于通过在数据库中存储相同内容节省编写代码时间,并通过传递参数获得所需输出。

The MS SQL Server Stored procedure is used to save time to write code again and again by storing the same in database and also get the required output by passing parameters.

Syntax

以下是存储过程创建的基本语法。

Following is the basic syntax of Stored procedure creation.

Create procedure <procedure_Name>
As
Begin
<SQL Statement>
End
Go

Example

可以将 CUSTOMERS 表视为包含以下记录。

Consider the CUSTOMERS table having the following records.

ID  NAME       AGE       ADDRESS            SALARY
1   Ramesh     32        Ahmedabad          2000.00
2   Khilan     25        Delhi              1500.00
3   kaushik    23        Kota               2000.00
4   Chaitali   25        Mumbai             6500.00
5   Hardik     27        Bhopal             8500.00
6   Komal      22        MP                 4500.00
7   Muffy      24        Indore             10000.00

以下命令是一个示例,它将从 Testdb 数据库中的 CUSTOMERS 表中获取所有记录。

Following command is an example which would fetch all records from the CUSTOMERS table in Testdb database.

CREATE PROCEDURE SelectCustomerstabledata
AS
SELECT * FROM Testdb.Customers
GO

以上命令将生成以下输出。

The above command will produce the following output.

ID  NAME       AGE       ADDRESS           SALARY
1   Ramesh     32        Ahmedabad         2000.00
2   Khilan     25        Delhi             1500.00
3   kaushik    23        Kota              2000.00
4   Chaitali   25        Mumbai            6500.00
5   Hardik     27        Bhopal            8500.00
6   Komal      22        MP                4500.00
7   Muffy      24        Indore            10000.00

T-SQL - Transactions

transaction 是针对数据库执行的一项工作单元。事务是由用户手动或由某种数据库程序自动以逻辑顺序执行的工作单元或工作序列。

A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program.

事务是向数据库传播一项或多项更改的过程。例如,如果您正在创建记录或更新记录或从表中删除记录,那么您正在对表执行事务。控制事务以确保数据完整性并处理数据库错误非常重要。

A transaction is the propagation of one or more changes to the database. For example, if you are creating a record or updating a record or deleting a record from the table, then you are performing a transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors.

实际上,您会将许多 SQL 查询合并到一个组中,并将它们全部作为一个事务的一部分一起执行。

Practically, you will club many SQL queries into a group and you will execute all of them together as a part of a transaction.

Properties of Transactions

事务具有以下四个标准属性,通常用首字母缩写词 ACID 提到 -

Transactions have the following four standard properties, usually referred to by the acronym ACID −

  1. Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure, and previous operations are rolled back to their former state.

  2. Consistency − Ensures that the database properly changes state upon a successfully committed transaction.

  3. Isolation − Enables transactions to operate independently of and transparent to each other.

  4. Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure.

Transaction Control

有以下用于控制事务的命令 −

There are following commands used to control transactions −

  1. COMMIT − To save the changes.

  2. ROLLBACK − To roll back the changes.

  3. SAVEPOINT − Creates points within groups of transactions in which to ROLLBACK.

  4. SET TRANSACTION − Places a name on a transaction.

事务控制命令仅用于 DML 命令 INSERT、UPDATE 和 DELETE。它们不能用于创建表或删除表,因为这些操作会自动提交到数据库中。

Transactional control commands are only used with the DML commands INSERT, UPDATE and DELETE only. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database.

为了在 MS SQL Server 中使用事务控制命令,我们必须使用“begin tran”或“begin transaction”命令开始事务,否则这些命令将不起作用。

In order to use transactional control commands in MS SQL Server, we have to begin transaction with ‘begin tran’ or begin transaction command otherwise these commands will not work.

COMMIT Command

COMMIT 命令用于将由事务调用的更改保存到数据库的事务命令。此命令将自上次 COMMIT 或 ROLLBACK 命令以来所有事务保存到数据库。

The COMMIT command is the transactional command used to save changes invoked by a transaction to the database. This command saves all transactions to the database since the last COMMIT or ROLLBACK command.

Syntax

以下是 COMMIT 命令的语法。

Following is the syntax for COMMIT command.

COMMIT;

Example

可以将 CUSTOMERS 表视为包含以下记录。

Consider the CUSTOMERS table having the following records.

ID  NAME       AGE       ADDRESS           SALARY
1   Ramesh     32        Ahmedabad         2000.00
2   Khilan     25        Delhi             1500.00
3   kaushik    23        Kota              2000.00
4   Chaitali   25        Mumbai            6500.00
5   Hardik     27        Bhopal            8500.00
6   Komal      22        MP                4500.00
7   Muffy      24        Indore            10000.00

以下命令示例将从表中删除年龄 = 25 的记录,然后在数据库中提交更改。

Following command example will delete records from the table having age = 25 and then COMMIT the changes in the database.

Begin Tran
DELETE FROM CUSTOMERS
   WHERE AGE = 25
COMMIT

最后将从表中删除两行,并且 SELECT 语句将生成以下输出。

As a result, two rows from the table would be deleted and SELECT statement will produce the following output.

ID  NAME       AGE       ADDRESS           SALARY
1   Ramesh     32        Ahmedabad         2000.00
3   kaushik    23        Kota              2000.00
5   Hardik     27        Bhopal            8500.00
6   Komal      22        MP                4500.00
7   Muffy      24        Indore            10000.00

ROLLBACK Command

ROLLBACK 命令是用于撤消尚未保存到数据库的事务的事务命令。该命令只能用于自上次发出 COMMIT 或 ROLLBACK 命令以来撤消事务。

The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. This command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued.

Syntax

以下是 ROLLBACK 命令的语法。

Following is the syntax for ROLLBACK command.

ROLLBACK

Example

可以将 CUSTOMERS 表视为包含以下记录。

Consider the CUSTOMERS table having the following records.

ID  NAME       AGE       ADDRESS            SALARY
1   Ramesh     32        Ahmedabad          2000.00
2   Khilan     25        Delhi              1500.00
3   kaushik    23        Kota               2000.00
4   Chaitali   25        Mumbai             6500.00
5   Hardik     27        Bhopal             8500.00
6   Komal      22        MP                 4500.00
7   Muffy      24        Indore             10000.00

以下命令示例将从表中删除年龄 = 25 的记录,然后在数据库中回滚更改。

Following command example will delete records from the table having age = 25 and then ROLLBACK the changes in the database.

Begin Tran
DELETE FROM CUSTOMERS
   WHERE AGE = 25;
ROLLBACK

最后,删除操作将不影响表,并且 SELECT 语句将生成以下结果。

As a result, delete operation will not impact the table and SELECT statement will produce the following result.

ID  NAME       AGE       ADDRESS          SALARY
1   Ramesh     32        Ahmedabad        2000.00
2   Khilan     25        Delhi            1500.00
3   kaushik    23        Kota             2000.00
4   Chaitali   25        Mumbai           6500.00
5   Hardik     27        Bhopal           8500.00
6   Komal      22        MP               4500.00
7   Muffy      24        Indore           10000.00

SAVEPOINT Command

SAVEPOINT 是事务中的一个点,在该点上您可以将事务回滚到某个点,而无需回滚整个事务。

SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction.

Syntax

以下是 SAVEPOINT 命令的语法。

Following is the syntax for SAVEPOINT command.

SAVE TRANSACTION SAVEPOINT_NAME

此命令仅用于在事务语句中创建 SAVEPOINT。ROLLBACK 命令用于撤消一组事务。

This command serves only in the creation of a SAVEPOINT among transactional statements. The ROLLBACK command is used to undo a group of transactions.

以下是回滚到 SAVEPOINT 的语法。

Following is the syntax for rolling back to a SAVEPOINT.

ROLLBACK TO SAVEPOINT_NAME

在以下示例中,我们将从 CUSTOMERS 表中删除三条不同的记录。在每次删除之前,我们都必须创建一个 SAVEPOINT,以便我们可以在任何时间回滚到任何 SAVEPOINT,以将适当的数据返回到其原始状态。

In the following example, we will delete three different records from the CUSTOMERS table. We will have to create a SAVEPOINT before each delete, so that we can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state.

Example

考虑包含以下记录的 CUSTOMERS 表:

Consider the CUSTOMERS table having the following records −

ID  NAME       AGE       ADDRESS          SALARY
1   Ramesh     32        Ahmedabad        2000.00
2   Khilan     25        Delhi            1500.00
3   kaushik    23        Kota             2000.00
4   Chaitali   25        Mumbai           6500.00
5   Hardik     27        Bhopal           8500.00
6   Komal      22        MP               4500.00
7   Muffy      24        Indore           10000.00

以下是操作系列:

Following are the series of operations −

Begin Tran
SAVE Transaction SP1
Savepoint created.
DELETE FROM CUSTOMERS WHERE ID = 1
1 row deleted.
SAVE Transaction SP2
Savepoint created.
DELETE FROM CUSTOMERS WHERE ID = 2
1 row deleted.
SAVE Transaction SP3
Savepoint created.
DELETE FROM CUSTOMERS WHERE ID = 3
1 row deleted.

这三个删除操作已经发生,但是,我们改变了主意并决定回滚到我们标识为 SP2 的 SAVEPOINT。因为 SP2 是在第一次删除后创建的,所以最后两个删除操作被撤消了 -

The three deletions have taken place, however, we have changed our mind and decide to ROLLBACK to the SAVEPOINT that we identified as SP2. Because SP2 was created after the first deletion, the last two deletions are undone −

ROLLBACK Transaction SP2
Rollback complete.

请注意,由于我们回滚到了 SP2,因此只执行了第一次删除。

Notice that only the first deletion took place since we rolled back to SP2.

SELECT * FROM CUSTOMERS

选择了 6 行。

6 rows selected.

ID  NAME       AGE       ADDRESS          SALARY
2   Khilan     25        Delhi        1500.00
3   kaushik    23        Kota             2000.00
4   Chaitali   25        Mumbai           6500.00
5   Hardik     27        Bhopal           8500.00
6   Komal      22        MP               4500.00
7   Muffy      24        Indore           10000.00

SET TRANSACTION Command

SET TRANSACTION 命令可用于启动数据库事务。此命令用于指定后续事务的特性。

SET TRANSACTION command can be used to initiate a database transaction. This command is used to specify characteristics for the transaction that follows.

Syntax

以下是 SET TRANSACTION 的语法。

Following is the syntax for SET TRANSACTION.

SET TRANSACTION ISOLATION LEVEL <Isolationlevel_name>

T-SQL - Indexes

Indexes 是数据库搜索引擎用于加快数据检索的特殊查找表。简而言之, index 是指向表中数据的指针。数据库中的索引与书末尾的索引非常相似。

Indexes are special lookup tables that the database search engine can use to speed up data retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to an index at the end of a book.

例如,如果你想要引用一本书中讨论某一特定主题的所有页面,你首先会参考索引,它按字母顺序列出所有主题,然后被引用到一个或多个特定的页码。

For example, if you want to reference all the pages in a book that discuss a certain topic, you first refer to the index, which lists all topics alphabetically and are then referred to one or more specific page numbers.

索引有助于加快 SELECT 查询和 WHERE 子句的速度,但会减慢数据输入速度,以及 UPDATE 和 INSERT 语句。可以在不影响数据的情况下创建或删除索引。

An index helps speed up SELECT queries and WHERE clauses, but it slows down data input, with UPDATE and INSERT statements. Indexes can be created or dropped with no effect on the data.

创建索引涉及使用 CREATE INDEX 语句,该语句允许你命名索引、指定表和要索引的列(一个或多个)以及指示索引是按升序还是降序。

Creating an index involves the CREATE INDEX statement, which allows you to name the index, to specify the table and which column or columns to index, and to indicate whether the index is in ascending or descending order.

索引也可以是唯一的,类似于 UNIQUE 约束,其中索引禁止在列或有索引列组合中重复条目。

Indexes can also be unique, similar to the UNIQUE constraint, in that the index prevents duplicate entries in the column or combination of columns on which there’s an index.

CREATE INDEX Command

以下是 CREATE INDEX 的基本语法。

Following is the basic syntax of CREATE INDEX.

Syntax

CREATE INDEX index_name ON table_name

Single-Column Indexes

单列索引是基于仅一个表列创建的。以下是其基本语法。

A single-column index is one that is created based on only one table column. Following is the basic syntax.

Syntax

CREATE INDEX index_name
ON table_name (column_name)

Example

CREATE INDEX singlecolumnindex
ON customers (ID)

Unique Indexes

唯一索引不仅用于性能,还用于数据完整性。唯一索引不允许将任何重复值插入表中。以下是其基本语法。

Unique indexes are used not only for performance, but also for data integrity. A unique index does not allow any duplicate values to be inserted into the table. Following is the basic syntax.

Syntax

CREATE UNIQUE INDEX index_name
on table_name (column_name)

Example

CREATE UNIQUE INDEX uniqueindex
on customers (NAME)

Composite Indexes

复合索引是对表中的两个或多个列进行的索引。以下是其基本语法。

A composite index is an index on two or more columns of a table. Following is the basic syntax.

Syntax

CREATE INDEX index_name on table_name (column1, column2)

Example

CREATE INDEX compositeindex
on customers (NAME, ID)

无论创建单列索引还是复合索引,都要考虑在查询的 WHERE 子句中可能非常频繁地用作筛选条件的列。

Whether to create a single-column index or a composite index, take into consideration the column(s) that you may use very frequently in a query’s WHERE clause as filter conditions.

如果只使用了一列,则应该选择单列索引。如果在 WHERE 子句中经常将两列或更多列用作筛选条件,那么复合索引将是最佳选择。

Should there be only one column used, a single-column index should be the choice. Should there be two or more columns that are frequently used in the WHERE clause as filters, the composite index would be the best choice.

Implicit Indexes

隐式索引是对象创建时由数据库服务器自动创建的索引。对于主键约束和唯一约束会自动创建索引。

Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints.

DROP INDEX Command

可以使用 MS SQL SERVER DROP 命令删除索引。删除索引时应小心,因为这可能会降低或提升性能。

An index can be dropped using MS SQL SERVER DROP command. Care should be taken when dropping an index because performance may be slowed or improved.

Syntax

以下是基本语法。

Following is the basic syntax.

DROP INDEX tablename.index_name

When to Avoid Indexes?

尽管索引旨在提高数据库性能,但在某些情况下应避免使用它们。以下指导原则指出了在什么时候应重新考虑使用索引−

Although indexes are intended to enhance the performance of databases, there are times when they should be avoided. The following guidelines indicate when the use of an index should be reconsidered −

  1. Indexes should not be used on small tables.

  2. Tables that have frequent, large batch update or insert operations should not be indexed.

  3. Indexes should not be used on columns that contain a high number of NULL values.

  4. Columns that are frequently manipulated should not be indexed.

T-SQL - Functions

MS SQL Server 有许多内置函数用于对字符串或数字数据执行处理。以下是所有有用的 SQL 内置函数的列表:

MS SQL Server has many built-in functions to perform processing on string or numeric data. Following is the list of all useful SQL built-in functions −

  1. SQL Server COUNT Function − The SQL Server COUNT aggregate function is used to count the number of rows in a database table.

  2. SQL Server MAX Function − The SQL Server MAX aggregate function allows to select the highest (maximum) value for a certain column.

  3. SQL Server MIN Function − The SQL Server MIN aggregate function allows to select the lowest (minimum) value for a certain column.

  4. SQL Server AVG Function − The SQL Server AVG aggregate function selects the average value for certain table column.

  5. SQL Server SUM Function − The SQL Server SUM aggregate function allows selecting the total for a numeric column.

  6. SQL Server SQRT Function − This is used to generate a square root of a given number.

  7. SQL Server RAND Function − This is used to generate a random number using SQL command.

  8. SQL Server CONCAT Function − This is used to concatenate multiple parameters to a single parameter.

  9. SQL Server Numeric Functions − Complete list of SQL functions required to manipulate numbers in SQL.

  10. SQL Server String Functions − Complete list of SQL functions required to manipulate strings in SQL.

T-SQL - String Functions

MS SQL Server 字符串函数可应用于字符串值,或将返回字符串值或数字数据。

MS SQL Server String functions can be applied on string value or will return string value or numeric data.

以下是字符串函数及其示例列表。

Following is the list of String functions with examples.

ASCII()

字符表达式的输出是 ASCII 码值。

Ascii code value will come as output for a character expression.

Example

以下查询将给出给定字符的 ASCII 码值。

The following query will give the Ascii code value of a given character.

Select ASCII ('word')

CHAR()

输出是给定 ASCII 码值或整数对应的字符。

Character will come as output for given Ascii code or integer.

Example

以下查询将给出给定整数对应的字符。

The following query will give the character for a given integer.

Select CHAR(97)

NCHAR()

输出是给定整数对应的 Unicode 字符。

Unicode character will come as output for a given integer.

Example

以下查询将给出给定整数对应的 Unicode 字符。

The following query will give the Unicode character for a given integer.

Select NCHAR(300)

CHARINDEX()

给定字符串表达式中给定搜索表达式的起始位置将作为输出。

Starting position for given search expression will come as output in a given string expression.

Example

以下查询将给出给定字符串表达式“KING”中字符“G”的起始位置。

The following query will give the starting position of 'G' character for given string expression 'KING'.

Select CHARINDEX('G', 'KING')

LEFT()

给定字符串的由左起指定数量字符的左侧将显示为给定字符串的输出。

Left part of the given string till the specified number of characters will come as output for a given string.

Example

以下查询将给定字符串“WORLD”中指定的 4 个字符数量的“WORL”字符串。

The following query will give the 'WORL' string as mentioned 4 number of characters for given string 'WORLD'.

Select LEFT('WORLD', 4)

RIGHT()

给定字符串的由右起指定数量字符的右侧将显示为给定字符串的输出。

Right part of the given string till the specified number of characters will come as output for a given string.

Example

以下查询将给定字符串“INDIA”中指定的 3 个字符数量的“DIA”字符串。

The following query will give the 'DIA' string as mentioned 3 number of characters for given string 'INDIA'.

Select RIGHT('INDIA', 3)

SUBSTRING()

基于给定字符串的起始位置值和长度值的字符串部分将显示为给定字符串的输出。

Part of a string based on the start position value and length value will come as output for a given string.

Example

以下查询将给定字符串“WORLD”、“INDIA”和“KING”分别指定的 (1,3)、(3,3) 和 (2,3) 起始和长度值显示为“WOR”、“DIA”和“ING”字符串。

The following queries will give the 'WOR', 'DIA', 'ING' strings as we mentioned (1,3), (3,3) and (2,3) as start and length values respectively for given strings 'WORLD', 'INDIA' and 'KING'.

Select SUBSTRING ('WORLD', 1,3)
Select SUBSTRING ('INDIA', 3,3)
Select SUBSTRING ('KING', 2,3)

LEN()

给定字符串表达式的字符数量将显示为输出。

Number of characters will come as output for a given string expression.

Example

以下查询将给出“HELLO”字符串表达式的 5。

The following query will give the 5 for the 'HELLO' string expression.

Select LEN('HELLO')

LOWER()

小写字符串将显示为给定字符串数据的输出。

Lowercase string will come as output for a given string data.

Example

以下查询将针对“SQLServer”字符数据给出“sqlserver”。

The following query will give the 'sqlserver' for the 'SQLServer' character data.

Select LOWER('SQLServer')

UPPER()

大写字符串将显示为给定字符串数据的输出。

Uppercase string will come as output for a given string data.

Example

以下查询将针对“SqlServer”字符数据给出“SQLSERVER”。

The following query will give the 'SQLSERVER' for the 'SqlServer' character data.

Select UPPER('SqlServer')

LTRIM()

删除前导空格后,字符串表达式将显示为给定字符串数据的输出。

String expression will come as output for a given string data after removing leading blanks.

Example

以下查询将针对“ WORLD”字符数据给出“WORLD”。

The following query will give the 'WORLD' for the '   WORLD' character data.

Select LTRIM('   WORLD')

RTRIM()

删除尾随空格后,字符串表达式将显示为给定字符串数据的输出。

String expression will come as output for a given string data after removing trailing blanks.

Example

以下查询将针对“INDIA ”字符数据给出“INDIA”。

The following query will give the 'INDIA' for the 'INDIA   ' character data.

Select RTRIM('INDIA   ')

REPLACE()

用指定字符替换指定字符的所有实例后,字符串表达式将显示为给定字符串数据的输出。

String expression will come as output for a given string data after replacing all occurrences of specified character with specified character.

Example

以下查询将针对“INDIA”字符串数据给出“KNDKA”字符串。

The following query will give the 'KNDKA' string for the 'INDIA' string data.

Select REPLACE('INDIA', 'I', 'K')

REPLICATE()

重复字符串表达式将显示为给定字符串数据带有指定次数的输出。

Repeat string expression will come as output for a given string data with specified number of times.

Example

以下查询将为“WORLD”字符串数据提供“WORLDWORLD”字符串。

The following query will give the 'WORLDWORLD' string for the 'WORLD' string data.

Select REPLICATE('WORLD', 2)

REVERSE()

反向字符串表达式将成为给定字符串数据的输出。

Reverse string expression will come as output for a given string data.

Example

以下查询将为“WORLD”字符串数据提供“DLROW”字符串。

The following query will give the 'DLROW' string for the 'WORLD' string data.

Select REVERSE('WORLD')

SOUNDEX()

返回四字符(SOUNDEX)代码以评估两个给定字符串的相似度。

Returns four-character (SOUNDEX) code to evaluate the similarity of two given strings.

Example

以下查询将为“Smith”、“Smyth”字符串提供“S530”。

The following query will give the 'S530' for the 'Smith', 'Smyth' strings.

Select SOUNDEX('Smith'), SOUNDEX('Smyth')

DIFFERENCE()

给定两个表达式将提供整数值作为输出。

Integer value will come as output of given two expressions.

Example

以下查询将为“Smith”、“Smyth”表达式提供 4。

The following query will give the 4 for the 'Smith', 'Smyth' expressions.

Select Difference('Smith','Smyth')

Note - 如果输出值为 0,则表示给定的 2 个表达式之间相似性较弱或没有相似性。

Note − If the output value is 0 it indicates weak or no similarity between give 2 expressions.

SPACE()

字符串将以指定数量的空间作为输出。

String will come as output with the specified number of spaces.

Example

以下查询将提供“I LOVE INDIA”。

The following query will give the 'I LOVE INDIA'.

Select 'I'+space(1)+'LOVE'+space(1)+'INDIA'

STUFF()

在从起始字符替换到指定字符长度后,字符串表达式将作为给定字符串数据的输出出现。

String expression will come as output for a given string data after replacing from starting character till the specified length with specified character.

Example

以下查询将为“ABCDEFGH”字符串数据提供“AIJKFGH”字符串,其中起始字符和长度分别为 2 和 4,“IJK”为指定的 target 字符串。

The following query will give the 'AIJKFGH' string for the 'ABCDEFGH' string data as per given starting character and length as 2 and 4 respectively and 'IJK' as specified target string.

Select STUFF('ABCDEFGH', 2,4,'IJK')

STR()

字符数据将作为给定数字数据的输出出现。

Character data will come as output for the given numeric data.

Example

根据指定的长度为 6 和 decimal 为 2,以下查询将为给定的 187.369 提供 187.37。

The following query will give the 187.37 for the given 187.369 based on specified length as 6 and decimal as 2.

Select STR(187.369,6,2)

UNICODE()

给定表达式的第一个字符将作为输出提供整数值。

Integer value will come as output for the first character of given expression.

Example

以下查询将为“RAMA”表达式提供 82。

The following query will give the 82 for the 'RAMA' expression.

Select UNICODE('RAMA')

QUOTENAME()

给定的字符串将以指定的定界符作为输出出现。

Given string will come as output with the specified delimiter.

Example

以下查询将为给定的“RAMA”字符串提供“RAMA”,因为我们将双引号指定为定界符。

The following query will give the "RAMA" for the given 'RAMA' string as we specified double quote as delimiter.

Select QUOTENAME('RAMA','"')

PATINDEX()

需要从给定的表达式中指定“I”位置作为第一次出现的起始位置。

Starting position of the first occurrence from the given expression as we specified 'I' position is required.

Example

以下查询将为“INDIA”提供 1。

The following query will give the 1 for the 'INDIA'.

Select PATINDEX('I%','INDIA')

FORMAT()

给定的表达式将以指定格式作为输出。

Given expression will come as output with the specified format.

Example

以下查询将针对 getdate 函数按指定格式提供“2015 年 11 月 16 日,星期一”,其中“D”表示星期名。

The following query will give the ' Monday, November 16, 2015' for the getdate function as per specified format with 'D' refers weekday name.

SELECT FORMAT ( getdate(), 'D')

CONCAT()

连接给定的参数值后,将作为输出提供单个字符串。

Single string will come as output after concatenating the given parameter values.

Example

以下查询将针对给定的参数提供“A,B,C”。

The following query will give the 'A,B,C' for the given parameters.

Select CONCAT('A',',','B',',','C')

T-SQL - Date Functions

以下是 MS SQL Server 中的日期函数列表。

Following is the list of date functions in MS SQL Server.

GETDATE()

它将返回当前日期和时间。

It will return the current date along with time.

Syntax

上述函数的语法 -

Syntax for the above function −

GETDATE()

Example

以下查询将返回 MS SQL Server 中的当前日期和时间。

The following query will return the current date along with time in MS SQL Server.

Select getdate() as currentdatetime

DATEPART()

它将返回日期或时间的局部。

It will return the part of date or time.

Syntax

上述函数的语法 -

Syntax for the above function −

DATEPART(datepart, datecolumnname)

Example

Example 1 - 以下查询将返回 MS SQL Server 中的当前日期局部。

Example 1 − The following query will return the part of current date in MS SQL Server.

Select datepart(day, getdate()) as currentdate

Example 2 - 以下查询将返回 MS SQL Server 中的当前月份局部。

Example 2 − The following query will return the part of current month in MS SQL Server.

Select datepart(month, getdate()) as currentmonth

DATEADD()

它将通过添加或减去日期和时间间隔来显示日期和时间。

It will display the date and time by add or subtract date and time interval.

Syntax

上述函数的语法 -

Syntax for the above function −

DATEADD(datepart, number, datecolumnname)

Example

以下查询将返回 MS SQL Server 中从当前日期和时间算起 10 天后的日期和时间。

The following query will return the after 10 days date and time from the current date and time in MS SQL Server.

Select dateadd(day, 10, getdate()) as after10daysdatetimefromcurrentdatetime

DATEDIFF()

它将显示两个日期之间的日期和时间。

It will display the date and time between two dates.

Syntax

上述函数的语法 -

Syntax for the above function −

DATEDIFF(datepart, startdate, enddate)

Example

以下查询将返回 MS SQL Server 中 2015-11-16 和 2015-11-11 日期之间的小时差。

The following query will return the difference of hours between 2015-11-16 and 2015-11-11 dates in MS SQL Server.

Select datediff(hour, 2015-11-16, 2015-11-11) as
differencehoursbetween20151116and20151111

CONVERT()

它将以不同的格式显示日期和时间。

It will display the date and time in different formats.

Syntax

上述函数的语法 -

Syntax for the above function −

CONVERT(datatype, expression, style)

Example

以下查询将以不同的格式返回 MS SQL Server 中的日期和时间。

The following queries will return the date and time in different format in MS SQL Server.

SELECT CONVERT(VARCHAR(19),GETDATE())
SELECT CONVERT(VARCHAR(10),GETDATE(),10)
SELECT CONVERT(VARCHAR(10),GETDATE(),110)

T-SQL - Numeric Functions

MS SQL Server数值函数可以对数值数据进行操作,并将返回数值数据。

MS SQL Server numeric functions can be applied on numeric data and will return numeric data.

以下是带示例的数值函数列表。

Following is the list of Numeric functions with examples.

ABS()

对于数值表达式,绝对值将作为输出。

Absolute value will come as output for numeric expression.

Example

以下查询将给出绝对值。

The following query will give the absolute value.

Select ABS(-22)

ACOS()

反正弦值将作为指定数值表达式的输出。

Arc cosine value will come as output for the specified numeric expression.

Example

以下查询将给出0的反正弦值。

The following query will give the arc cosine value of 0.

Select ACOS(0)

ASIN()

反余弦值将作为指定数值表达式的输出。

Arc sine value will come as output for the specified numeric expression.

Example

以下查询将给出0的反余弦值。

The following query will give the arc sine value of 0.

Select ASIN(0)

ATAN()

弧正切值将作为指定的数字表达式的输出。

Arc tangent value will come as output for the specified numeric expression.

Example

以下查询将给出一个弧切 0 的数值。

The following query will give the arc tangent value of 0.

Select ATAN(0)

ATN2()

特定数值表达式的值将作为输出值以所有象限上的弧切值给出的。

Arc tangent value in all four quadrants will come as output for the specified numeric expression.

Example

以下查询将给出一个 0 的所有四个象限内的弧切值。

The following query will give the arc tangent value in all four quadrants of 0.

Select ATN2(0, -1)

可以将 CUSTOMERS 表视为包含以下记录。

Consider the CUSTOMERS table having the following records.

ID  NAME       AGE       ADDRESS             SALARY
1   Ramesh     32        Ahmedabad           2000.00
2   Khilan     25        Delhi               1500.00
3   kaushik    23        Kota                2000.00
4   Chaitali   25        Mumbai              6500.00
5   Hardik     27        Bhopal              8500.00
6   Komal      22        MP                  4500.00
7   Muffy      24        Indore              10000.00

BETWEEN()

如果给出的两个表达式之间存在值域,它将成为一个输出。

If the values exist between given two expressions then those will be come as output.

Example

以下查询将给出以下输出。

The following query will give the following output.

SELECT salary from customers where salary between 2000 and 8500

Output

salary
2000.00
2000.00
6500.00
8500.00
4500.00

MIN()

给定表达式的最小值将作为输出。

Minimum value will come as output from the given expression.

Example

以下查询将给出一个针对客户表中给定的“工资”表达式的“1500.00”。

The following query will give '1500.00' for the given 'salary' expression from the customers table.

Select MIN(salary)from CUSTOMERS

MAX()

给定的表达式的最大值将作为输出。

Maximum value will come as output from the given expression.

Example

以下查询将给出针对客户表中给定的“工资”表达式的“10000.00”。

The following query will give '10000.00' for the given 'salary' expression from the customers table.

Select MAX(salary)from CUSTOMERS

SQRT()

给定数值表达式的平方根将作为输出。

Square root of the given numeric expression will come as output.

Example

以下查询将给出一个针对 4 的数值表达式的 2。

The following query will give 2 for the given 4 numeric expression.

Select SQRT(4)

PI()

PI 值将作为输出。

PI value will come as output.

Example

以下查询将给出一个 3.14159265358979 针对 PI 值。

The following query will give 3.14159265358979 for the PI value.

Select PI()

CEILING()

四舍五入小数后的给定值将作为输出,这将是下一个最高值。

Given value will come as output after rounding the decimals which is the next highest value.

Example

以下查询将给出一个针对 123.25 值的 124。

The following query will give 124 for the given 123.25 value.

Select CEILING(123.25)

FLOOR()

四舍五入后给定值将作为输出,它将小于或等于表达式。

Given value will come as output after rounding the decimals which is less than or equal to the expression.

Example

以下查询将给出一个针对 123.25 值的 123。

The following query will give 123 for the given 123.25 value.

Select FLOOR(123.25)

LOG()

给定表达式的自然对数将作为输出。

Natural logarithm of the given expression will come as output.

Example

以下查询将给出一个针对给定值 1 的 0。

The following query will give 0 for the given 1 value.

Select LOG(1)