SQL Learning 2

Source: Internet
Author: User

* SQL Server does not support transactions compared to mysqlmysql, no views, no stored procedures and triggers, no user-defined functions on the database side, and cannot fully use standard SQL syntax

* So here I am using SQL Server Management Studio to do some work on SQL Server

T-SQL encoding

1: Local variables and global variables

* Global variables are provided by the system and are pre-declared and are distinguished from local variables by adding "@@" symbols before the variable names. Users can only use global variables and cannot modify the values of global variables. Global variables are scoped to the entire SQL Server system

* Local variables are defined by the user and are distinguished from global variables by adding the "@" symbol before the variable name

Example 1: Declaring a variable @testdatetime, placing the value of the GETDATE () function in a variable, and finally outputting the value of the variable @testdatetime

Declare @testDateTime varchar (in) Select @testDateTime = getdate  Select@testDateTimeas' current time 'go 

Run results

Example 2: Declaring a variable @getage, mytestuser the value of the age of the field with the ID 2 in the table into the variable @getage, and finally outputting the @getage value

Declare @getAge int Select @getAge =  from where id=2Select@getAgeas'2nd ' age  'go

Run results

2: Using Operators

Example 1: Assigning the value of an expression 67%31 to a variable @result

Declare @result int Select @result =  the %  to Select @result  as ' Results ' Go

Run results

Example 2: Defining variables x and y, assigning a value to a variable, and then finding the result of two variables with, or, XOR

Declare @x int,@y intSet @x = 2Set @y = 7Select @x & @y  as 'with the',       @x | @y  as 'or',       @x ^ @y  as 'XOR or'

Run results

Example 3: Define variables x and y, assign a value to a variable, and then find the smaller of the two variables

Declare @x int,@y intSet @x =  ASet @y = 7if @x < @ySelect @x  as 'Small Data'ElseSelect @y  as 'Small Data'

Run results

Example 4: Connecting two strings using a join operator (+)

--Note that the length of the variable x, if the length is not enough, the data can not be fully displayedDeclare @x varchar( -)Set @x = 'The eight-tzu'+'of the'+'Blog Park'Select @x  as 'results of data connections'

Run results

3:case statements

Example 1: If the age is less than 20 years old show "teenager", if the age between 20 to 30 years old show "Youth", if the age of 30 years old show "middle-aged"

/*Note that 1: there is a comma-separated 2 between the case and the field: You cannot use the && representation between when and then, so you can invert the condition to avoid age<30&&age>20*/SelectName,age, Case   whenAge> -  Then 'aged' whenAge> -  Then 'Youth' whenAge< -  Then 'Juvenile'End  as  Level fromMytestuser

Run results

4:while indicates a loop

Example 1: Displays each character in the string "Minocycline" and its ASCII code

Declare @position int,@str varchar(Ten)Set @position = 1 --It is important to note that the value of the string in SQL starts from 1Set @str = 'The eight-tzu' while @position <=datalength(@str)--the length here is 8.    begin        Select SUBSTRING(@str,@position,1),        ASCII(SUBSTRING(@str,@position,1))        Set @position =@position+1    End

Run results

5:result statements

Result can exit unconditionally from a query or procedure and can exit from a procedure, batch, or statement block at any time without executing the statement after result

Example 1: Average age of users through stored procedures

--To Delete a stored procedureDrop procedureMypro--create a stored procedureCreate procedureMypro@num int as return(Select avg(age) fromMytestuserwhereId< @num)--Create a queryDeclare @avg int,@number intSet @number = 4exec @avg =Mypro@number --Pass the value of the variable num to the stored procedure and assign the result of the stored procedure to the variable avgSelect @avg  as 'average age' 

The execution of the above SQL statement one, executes the result of creating the query

User-defined Functions

Example 1: Create a function to display user information for a larger age

--Delete a functionDrop functionShowmax--Create a functionCreate functionShowmax (@id1 int,@id2 int)returns  varchar( -)--Name of function--function Body as  begin       Declare @result varchar( -),@name1 varchar(Ten),@name2 varchar(Ten),@age1 varchar(Ten),@age2 varchar(Ten)      Select @age1 =Age@name1 =Name fromMytestuserwhereId= @id1      Select @age2 =Age@name2 =Name fromMytestuserwhereId= @id2      if(@age1<@age2)            Set @result = @name2 +'The age is:'+ @age2      Else            Set @result = @name1 +'The age is:'+ @age1      return @result   End/*Note that: 1: In the function name declaration of ID1 and ID2, in the functional body there is no need to declare can be used directly 2: Must be @age1 varchar, @age2 varchar (10) to convert the int type to a varchar type, So that the age with @name2 + ' is: ' Connected*/--using FunctionsSelectDbo.showmax (3,4) asMaxmess

Run results

Cursor

A cursor is actually a mechanism that extracts one record at a time from a result set that includes multiple data records

1: Type of cursor

1:t-sql Cursors

Used primarily for T-SQL scripts, stored procedures, and triggers. Mainly used on the server, by the client sent to the server T-SQL statements or batches, stored procedures, the T-SQL in the trigger management. Extracting data blocks or multiple rows of data is not supported

2:API Cursors

The main use on the server

3: Customer cursor

Primarily when you cache a result set on a client computer by using the

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------because T-SQL cursors and API cursors are used on the server side, also called server cursors or background cursors. Client-side cursors are also known as foreground cursors

Server cursors include: Static cursors, dynamic cursors, forward-only cursors, keyset-driven Cursors 4 types

2:5 Operations of cursors

DECLARE CURSOR--OPEN cursor--read CURSOR--close cursor (if you do not close the cursor, others can enter, very dangerous)--release the cursor

SQL Learning 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.