Article Directory
Transact-SQL.
While SQL Server supports the standard SQL language, it has been expanded by introducing Transact-SQL, or T-SQL for short, which is the core of using SQL Server. It can define variables, use control flow statements, custom functions and custom Defining stored procedures, etc., greatly expanded the functionality of SQL Server. In SQL Server-DBMS, stored procedures and triggers play an important role. Stored procedures and triggers are a collection of SQL statements and control flow statements.
SQL is the standard language of DBMS. Standard SQL statements can almost be applied to all RDBMS without modification, but it does not support process control, and it is sometimes inconvenient to use. Therefore, large-scale RDBMS are based on standard SQL and combine their own characteristics to introduce programmable and structured SQL languages, such as T-SQL for SQL Server here, and PL/SQL for Oracle 11g. The main purpose of T-SQL is to design program blocks that can be executed in the background on the server side, such as stored procedures and triggers .
variable.
If you are familiar with high-level languages, you will not be unfamiliar with variables. Like many high-level languages, variables in SQL Server are divided into global variables and local variables, but there are some differences. Global variables are defined and maintained by the system . Users can only use pre-explained and defined global variables, and the permissions are [read-only], that is, users can only read, but cannot modify or log off; local variables are defined and Assignment , and its purpose is almost the same as that of variables in high-level languages. One thing to note is that when using global variables in SQL Server, they need to be in the form of [@@variable name], and local variables need to be in the form of [@variable name].
Local variables.
The name of a local variable cannot be the same as a global variable, and its scope is limited to the batch, stored procedure or trigger where it is declared, and the local variable name in SQL Server is not case sensitive. Local variables are often used to store data obtained from queries, as temporary variables during program execution.
- [Declaration method] T-SQL provides
DECLARE
statements to declare local variables, and variable names must be prefixed with @. The syntax format is as follows, whichTYPE
can be all data types supported by SQL Server:
DECLARE @Var_1 TYPE,@Var_2 TYPE,...,@Var_n TYPE
- [Assignment method] T-SQL does not support
Var=Value
such assignment methods in many high-level languages . Instead, you must useSELECT
orSET
commands to assign values to variables. The syntax format is as follows:
SELECT @Var=Value
SET @Var=Value
Operator.
The operators in T-SQL are basically the same as those in C language.
[Arithmetic operator] The arithmetic operator performs mathematical operations on two expressions, and the
expressions involved in the operation must be numeric data types or other data types capable of arithmetic operations.
[Comparison operator]
[Logical operator]
【Bitwise Operator】
[Unary operator]
[Priority and associativity]
Batch statement.
Batch processing is a unit that contains one or more T-SQL statements, all of which are integrated into an execution plan. All statements in a batch are either put together and passed parsing, or none of the statements will be executed. The syntax of batch processing is to use GO
statements to separate multiple SQL statements GO
. The code between every two statements is a batch processing unit, and each batch processing unit will be treated separately, so there will be no errors in a unit. , Causing all statements to be stopped, for example:
USE Teach
GO
SELECT * FROM SC
SELECT COUNT(*) FROM S
GO
Flow control statement.
The process control statements used by T-SQL are similar to common programming languages, enabling it to control program execution and process branching. There are mainly the following control statements:
- BEGIN…END
- IF…ELSE
- CASE
- WHILE
- WAITFOR
- GOTO
- RETURN
● Use the BEGIN...END statement to create a program block composed of one statement or multiple statements. The syntax format is as follows:
BEGIN
<命令行或程序块>
END
● Use the IF…ELSE statement to create a conditional statement. The syntax format is as follows, and the ELSE
clauses can also be omitted:
IF <条件表达式>
<命令行或程序块>
ELSE
<命令行或程序块>
[Example] Obtain the average score of student number S1 from the SC data table in the database Teach. If the score is equal to or equal to 60 points, output the "pass" information, otherwise, output the "fail" information.
USE Teach
GO
IF (SELECT AVG(SCORE)FROM SC WHERE SNO=‘S1’)>=60
PRINT ‘pass’
ELSE
PRINT ‘fail’
GO
IF
There is another variant of the IF EXISTS|NOTEXISTS
statement, which is actually the same as the ordinary statement IF
. Its syntax is as follows:
IF EXISTS|NOT EXISTS (SELECT 子查询)
<命令行或程序块>
ELSE
<命令行或程序块>
[Example] Read the record of student number S1 from the S table in the database Teach, if it exists, output "record exists", otherwise, output "record does not exist".
USE Teach
GO
DECLARE @message VARCHAR(255)
IF EXISTS (SELECT * FROM S WHERE SNO=‘S1’)
SET @message=‘存在记录’
ELSE
SET @message=‘不存在记录’
PRINT @message
GO
● When there are multiple conditional judgments, you can use a CASE
statement to CASE
find the corresponding expression by judging the value of the following expression WHEN
, and then execute THEN
the expression after execution, and then jump out after execution CASE
. If there is no ELSE
clause, all the comparison fails, feedback NULL
, if present ELSE
clause, ELSE
there is no match WHEN
, the contents of execution. The syntax format is as follows:
CASE <表达式>
WHEN <表达式> THEN <表达式>
…
WHEN <表达式> THEN <表达式>
ELSE <表达式>
END
[Example] Select SNO and Sex from the S table in the database Teach. If the Sex field is'male', output'M'; if it is'female', output'F'.
USE Teach
GO
SELECT SNO, Sex=
CASE sex
WHEN‘男’THEN ‘M’
WHEN‘女’THEN ‘F’
END
FROM S
GO
● WHILE…CONTINUE…BREAK
Statement, when a loop structure is needed, the WHILE statement can be used to judge WHILE
whether the loop is terminated or not through the post-conditional expression. If the loop is not over, execute BEGIN
and END
mark the content. The syntax is as follows:
WHILE <条件表达式>
BEGIN
<命令行或程序块>
[BREAK]
[CONTINUE]
[命令行或程序块]
END
[Example] Calculate and output the sum and number of the numbers divisible by 3 between 1-100.
DECLARE @s SMALLINT,@i SMALLINT,@nums SMALLINT
SET @s=0
SET @i=1
SET @nums=0
WHILE (@i<=100)
BEGIN
IF (@i%3=0)
BEGIN
SET @s=@s+@i
SET @nums=@nums+1
END
SET @i=@i+1
END
PRINT @s
PRINT @nums
● When the program needs to be blocked for a period of time, you can use the WAITFOR
implementation.
[Example] Wait for 1 hour, 2 minutes, and 3 seconds before executing the SELECT statement
WAITFOR DELAY '01:02:03'
SELECT * FROM S
[Example] Specify to start executing the SELECT statement at 11:24:00
WAITFOR TIME '11:24:00'
SELECT * FROM S
DELAY
: Used to set the waiting time, up to 24 hours;: TIME
Used to set the time point for waiting to end.
● Change the execution flow to the position specified by the label. The system skips GOTO
the following statement.
DECLARE @s SMALLINT,@i SMALLINT
SET @i=1
SET @s=0
BEG: /*标号*/
IF (@i<=10)
BEGIN
SET @s=@s+@i
SET @i=@i+1
GOTO BEG /*使程序跳转到标号为BEG的地方执行*/
END
PRINT @s
● You can use RETURN
exit at any position , and the system will not execute the RETURN
following statement.
The RETURN statement cannot return a NULL value. SQL Server reserves the return value between −1 and −99 for system use.
Common commands.
- BACKUP is used to back up the contents of the database or its transaction log to the storage medium (floppy disk, hard disk, tape, etc.).
- DBCC is used to verify database integrity, find errors, and analyze system usage.
- The EXECUTE or EXEC command is used to execute the stored procedure.
- The KILL command is used to terminate the execution of a certain process.
- The PRINT command returns a user-defined message to the client, that is, displays a string, local variable or global variable.
- RAISERROR is used to return the information specified by the user when the SQL Server system returns an error message.
- The SHUTDOWN command is used to stop the execution of SQL Server.
- The USE command is used to change the currently used database to the specified database.
- The SET command has two uses: it is used to assign values to local variables; it is used to set SQL Server processing options when the user executes SQL commands.
Built-in functions.
A function is a set of T-SQL statements that can complete a specific function and return the processing result. The processing result is called the "return value", and the processing procedure is called the "function body". Functions can be used to construct expressions, can appear in the select list of a SELECT statement, or in the conditions of the WHERE clause. The built-in functions of SQL Server include:
- Statistical function
- Arithmetic function
- String function
- Date function
- Custom function
Here are some commonly used built-in functions:
- The STDEV function returns the standard deviation of all data in the expression.
- The STDEVP function returns the overall standard deviation of all data in the expression.
- The ASCII function returns the ASCII code value of the leftmost character in a character expression.
- The CHAR function is used to convert ASCII codes into characters.
- The LOWER function is used to convert all strings to lowercase.
- The UPPER function is used to convert all strings to uppercase.
- The STR function is used to convert numeric data into character data.
- The LTRIM function is used to remove the spaces at the head of the string.
- The RTRIM function is used to remove spaces at the end of a string.
- The substring returned by the LEFT (character_expression, integer_expression) function is the part from the leftmost
integer_expression
character of the string to the first character. Correspondingly, the substring returned by the RIGHT (character_expression, integer_expression) function is the part from theinteger_expression
first character on the right side of the string to the last character. - The CHARINDEX (substring_expression, expression) function returns the starting position of a specified substring in the string.
User-defined functions.
- Create a scalar value function;
- Create inline table-valued functions;
- Multi-statement table-valued functions.
Numerical functions return a single data value; table-valued functions return a result set (table data type). The body of a scalar-valued function consists of one or more T-SQL statements, which BEGIN
start and END
end.
[Example] Customize a scalar function Fun1 to determine whether an integer is a prime number, if it is a prime number, the function returns 1, otherwise it returns 0, and the number to be determined is passed to the function through the parameter.
CREATE FUNCTION dbo.Fun1(@n AS INT)
RETURNS INT
AS
BEGIN
DECLARE @i INT
DECLARE @sign INT
SET @sign=1
SET @i=2
WHILE @i<=SQRT(@n)
BEGIN
IF @n % @i=0
BEGIN
SET @sign=0
BREAK
END
SET @i=@i+1
END
RETURN @sign
END
Call: SELECT dbo.Fun1(13).