当前位置:网站首页>Knowledge points in T-SQL
Knowledge points in T-SQL
2022-06-24 18:39:00 【MousseIn】
Tsql Knowledge points in
local variable
- Local variables must be marked with @ The prefix , Such as @age
- The use of local variables is also declared first , To assign a value
DECLARE @ Variable name data type
DECLARE @Name varcher(8)
DECLARE @seat int
assignment
The syntax of assignment is as follows :
SET @ Variable name = value -- similar UPDATE It is written in the same way as other assignment statements , Assign the value after the equal sign to the variable before the equal sign .
or
SELECT @ Variable name = value
In operations involving any local variable , Must be @ Put the character before the variable name .
Example :
SET @name = ' Zhang San '
SELECT @name = studentName From Student
WHERE studentNo = '10011';
SET Statements can only be assigned directly , Not to SELECT Statement to directly assign the query result to a variable .
SELECT Statements can be assigned directly .
- SELECT Statement can assign values to multiple variables at the same time , and SET Statement can assign values to only one variable at a time .
- When an expression returns multiple values ,SET Statements will report errors , and SELECT The last value is assigned to the variable .
- When the expression does not return a value ,SET The statement will be assigned to NULL,SELECT Statement will make the variable
Global variables
- Global variables must be marked with @@ The prefix , Such as @@error
- Global variables are defined and maintained by the system , Can only read , Do not modify , And the user cannot declare the definition
Even if I write @@ It is not a global variable
His writing @@ Variable names can also be assigned , But the system will think @ @ Variable name
Examples are as follows :
declare @@email varchar(10)
set @@email ='abc'
select @@email
-- The compiler can tell the difference ,@@email System identification as @ @email So it is not a global variable but a local variable
This is the basic global variable :
@@ERROR: the last one T-SQL Wrong error number
@@IDENTITY : Last inserted identification value
@@SERVERNAME: Name of the local server
@@VERSION:SQL Server Version information for
Data type conversion
To provide solutions to data type incompatibilities , The database provides a link for data type conversion . There are several ways .
cast The way :
CAST( expression AS data type )
Examples are as follows :
select 'student age is' + 10 -- Report errors
select 'student age is' + CAST(10 as varchar )-- Find out the data student age is 10
convert The way :
CONVERT( data type , expression , style )// The data type is the converted data type
Examples are as follows :
select 'student age is '+10; -- Report errors
select 'student age is '+ CONVERT(varchar,10,133) -- Find out the data student age is 10
But in the database "+" No. focuses more on computation than string splicing , If it's this form :
select '10'+10 -- The query result is 20
select CONVERT(int,10)+10 -- The query result is 20, Be careful int There are no extra styles in the type , So the style can be omitted .
Because of "+" More emphasis on calculation , It will not report an error but directly calculate the result .
Following example :
select CONVERT(varchar,RegisterTime) from users -- Convert date format to string format output
select CONVERT(varchar,RegisterTime,110) from users -- Change the format of the detected string to 110 style
select CONVERT(varchar,RegisterTime,2222) from users -- Style values have ranges, not just any one .
It shows that the style value has a range . And this style is mainly for the display of dates .
cast and convert The difference between :
cast There is no way to select the converted style .
and convert Prefer date format .
Branching structure
IF-ELSE sentence
take C# in if-else Replace the braces in the statement with BEGIN - END Sentence block
· ELSE It's optional
· If there are multiple statements , That's what we need BEGIN-END Sentence block .
Examples are as follows :
declare @num int
--set @num = 60
set @num = 70
if(@num > 60)
begin
-- If there is only one statement , You don't have to write BEGIN-END Sentence block
-- and C# equally , Will automatically read immediately following if The statement after the statement
print(@num)
print('OK')
select * from Users where UserStateId < @num
end
else
print('error')
--else
--print('error')
IF -ELSEIF sentence
Examples are as follows :
select * from Users
declare @num int
--set @num = 60
set @num = 70
IF(@num > 60)
BEGIN
print ('a')
-- If there is only one statement , You don't have to write BEGIN-END Sentence block
-- and C# equally , Will automatically read immediately following if The statement after the statement
--print(@num)
--print('OK')
--select * from Users where UserStateId < @num
END
else if( @num = 60)
BEGIN
print('b')
END
ELSE
BEGIN
print('c')
END
CASE - END sentence
The grammar is as follows
CASE
WHEN Conditions 1 THEN result 1
WHEN Conditions 2 THEN result 2
…
ELSE Other results
END
When not satisfied WHEN All the conditions of , use ELSE
ELSE: It means as if all WHEN The conditions are not TRUE If omitted, the result returned by ELSE And WHEN The conditions are FALSE when ,CASE Statement returns NULL
THEN It is not allowed to write other logical operations after .
CASE-END In the sentence , As long as one condition is met , The following conditions will not continue to run .
THEN Followed by a result , Suppose you follow a query statement , Returns a result set of multiple results , You're going to report a mistake . If the following query statement is a result , Then it can run successfully .
Examples are as follows :
select * , case
when UserRoleId = 1 then 'A'
when UserRoleId = 2 then 'B'
when UserRoleId = 3 then 'C'
else 'D'
end as 'level'
from Users
Loop statement
While sentence
grammar :
WHILE ( Conditions )
BEGIN
Sentence one
Sentence two
…
BREAK
END
Examples are as follows :
declare @sum int = 0
declare @i int = 1
while ( @i <=100)
begin
set @sum = @sum +@i
set @i= @i+1
continue
--return
--break
end
print @sum
Batch instructions GO
The batch :
It contains one or more SQL Groups of statements , Send one-time from the application to SQL Server perform
SQL Server To batch SQL Statement is compiled into an execution unit , This unit is called an execution plan .
Using batch processing can improve the execution effect of code , Usually, the code of related business will be stored in the same batch processing statement .
GO Must be a single line .
GO Is not a T-SQL command , Only commands recognized by the editing tool .
All statements start at the beginning of the script or the previous GO Statement starts compiling , Know the next one GO End of statement or script , Compile this code into an execution plan .
边栏推荐
- Two micro service interviews where small companies suffer losses
- Exception: Gradle task assembleDebug failed with exit code 1
- Wechat applet development - Implementation of rotation chart
- Knowledge points of 2022 system integration project management engineer examination: ITSS information technology service
- How can programmers reduce bugs in development?
- Business leaders compete for CIO roles
- Mariana Trench, Facebook's open source code analysis tool
- Redpacketframe and openmode packages
- (Video + graphics) introduction to machine learning series - Chapter 11 support vector machines
- Application service access configuration parameters
猜你喜欢

解决执行MapReduce程序控制台没有日志信息WARN Please initialize the log4j system properly

It is often blocked by R & D and operation? You need to master the 8 steps before realizing the requirements

Complete Guide to web application penetration testing

How to select the best test cases for automation?

JS deep understanding of scope
congratulate! The first dragon lizard community annual outstanding contribution award is announced. Check it now

如何在 R 中使用 Fisher 的最小显着性差异 (LSD)

2022 network security C module of the secondary vocational group scans the script of the surviving target aircraft (municipal, provincial and national)

Exception: Gradle task assembleDebug failed with exit code 1

JS string method
随机推荐
Eight recommended microservice testing tools
Location object
variable
An analysis of the comments on the TV series Douban by procedural apes
Sword finger offer 10- ii Frog jumping on steps
Vite+web3:报错出现ReferenceError: process is not defined
Get max value of a bit column - get max value of a bit column
High quality defect analysis: let yourself write fewer bugs
R language Quantitative Ecology redundancy analysis RDA analysis plant diversity species data visualization
Several key points for enterprises to pay attention to digital transformation
How to create a linear model prediction interval in R and visualize it
JS local storage
Leetcode topic [array] -216- combined sum III
Mariana Trench, Facebook's open source code analysis tool
Some knowledge of the beginning of 2022
云服务器类型怎么选,要考虑什么?
"2022" plans to change jobs and raise salary. It is necessary to ask interview questions and answers - browser
Four security issues of low code and no code development
Industry Cloud video editing software
Ten excellent business process automation tools for small businesses