search
HomeDatabaseMysql TutorialSqlServer 2005 T-SQL Query 学习笔记(1)

SqlServer 2005 T-SQL Query 学习笔记(1)

Select字句在逻辑上是SQL语句最后进行处理的最后一步,所以,以下查询会发生错误:

OrderDateOrderYearCustomerIDNumCusts
dboOrders
OrderYear

因为group by是在Select之前进行的,那个时候orderYear这个列并没有形成。

如果要查询成功,可以像下面进行修改:

OrderYearCustomerIDNumCusts
OrderDateOrderYearCustomerID
   dboOrdersD
OrderYear

还有一种很特殊的写法:

OrderYearCustomerIDNumCusts
OrderDateCustomerID
   dboOrders<u>D<strong>OrderYearCustomerID</strong></u>OrderYear

在作者眼里,他是非常喜欢这种写法的,因为更清晰,更明确,更便于维护。

在查询中使用参数定向产生一批结果,这个技巧没有什么好说的。

嵌套查询,在处理逻辑上是从里向外进行执行的。

多重引用,有可能你的SQL语句包含了多次从一个表进行查询后进行连接组合。比如你要比较每年的顾客数同先前年的顾客数的变化,所以你的查询就必须JOIN了2个相同的表的实例,这也是不可避免的。

Common Table Expressions (CTE)

CTE是在SQL2005新加入的一种表的表示类型。

它的定义如下:

WITH cte_name

AS

(

cte_query

)

outer_query_refferring to_cte_name;

注意:因为在标准的T-SQL语言中已经包含了WITH关键字,所以为了区分,CTE在语句的结尾加上了“;”作为停止符。

CTE实例一(结果集别名)

C OrderDateOrderYearCustomerID
 dboOrders
OrderYearCustomerIDNumCusts
C
OrderYear

当然,作者本人有更推荐的写法:

COrderYearCustomerIDOrderDateCustomerID
 dboOrders
OrderYearCustomerIDNumCusts
C
OrderYear

CTE实例二(多重CTEs)

C1 OrderDateOrderYearCustomerID
 dboOrders
C2 OrderYearCustomerIDNumCusts
 C1
 OrderYear
OrderYearNumCusts
C2
NumCusts 70

CTE实例三(多重引用)

YearlyCount OrderDateOrderYearCustomerIDNumCusts
 dboOrders
 OrderDateCurOrderYearCurNumCusts CurNumCustsPrvNumCusts PrvNumCustsCurNumCusts PrvNumCusts Growth
YearlyCount Cur
 YearlyCount Prv
  CurOrderYear PrvOrderYear 1

CTE实例四(修改数据)

1.把从customer表查询出来的结果,动态的组装进新表CustomersDups里:

dboCustomersDupsGO

CrossCustomers 1 cC1dboCustomers C1dboCustomers C2
cKeyColCustomerIDCompanyNameContactNameContactTitleCityRegionPostalCodeCountryPhoneFax
dboCustomersDups
CrossCustomers

2.使用CTE移除数据,只保留CustomerDups表里同一CustomerID里KeyCol为最大的记录。

JustDups dboCustomersDups C1
 KeyCol KeyColdboCustomersDups C2
   C2CustomerID C1CustomerIDJustDups

CTE实例五(对象容器)

即提供了封装的能力,有利于组件化的编程。作者额外的提醒,CTE无法直接内嵌,但是可以通过把CTE封装进一个对象容器里并从一个外部的CTE里对这容器的数据进行查询而实现内嵌。

作者也说明了,使用CTEs在VIEW和UDFs里是没有什么价值的。

有个例子,如下:

dboVYearCnt
YearCnt OrderDateOrderYearCustomerIDNumCusts
 dboOrders
 OrderDateYearCnt

CTE实例六(CTEs的递归)

作者给了一个例子,来讲述这个在SQL2005的新内容,CTEs的递归。

根据employeeId,返回此员工的信息,并包含所有下级员工的信息。(等级关系基于empolyeeId和reportsTo的属性)所返回的结果包含下列字段,employeeId,reportsTo,FirstName,LastName。

作者在这里,给予了一个最佳的索引方式:

idx_mgr_emp_ifname_ilname
 dboEmployeesReportsToEmployeeIDFirstNameLastName

作者的解释: 这个索引将通过一个单独的查询(局部扫描)来取得每个经理的直接下级。Include(FristName,LastName)加在这里,即是覆盖列。

小知识:什么Include索引?

Include索引是SQL2005的新功能。Include索引的列并不影响索引行的物理存储顺序,他们作为一个挂件‘挂在'索引行上。挂这些‘挂件'的目的在于,只需要扫描一把索引就获得了这些附加数据。

回到作者的例子上,下面是递归的代码:

EmpsCTE EmployeeIDReportsToFirstNameLastName
 dboEmployees
 EmployeeID 5
 EMPEmployeeIDEMPReportsToEMPFirstNameEMPLastName
 EmpsCTE MGR
  dboEmployees EMP
   EMPReportsTo MGREmployeeID
EmpsCTE

理解:一个递归的CTE包含了至少2个查询,第一个查询在CTE的身体里类似于一格锚点。这个锚点仅仅返回一个有效的表,并作为递归的一个锚。从上的例子看出来,锚点仅仅返回了一个employeeID = 5 的一行。然后的第2个查询是作为递归成员。当查询到下属成员的结果为空时,此递归结束。

如果你担心递归会造成永久循环,你可以使用下面的表达:

WITH cte_name AS (cte_body) outer_query OPTION (MAXRECURSION n);

默认的n为100,当n=0时,无限制。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Apr 16, 2025 am 12:20 AM

ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

MySQL: Database Management System vs. Programming LanguageMySQL: Database Management System vs. Programming LanguageApr 16, 2025 am 12:19 AM

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

MySQL: Managing Data with SQL CommandsMySQL: Managing Data with SQL CommandsApr 16, 2025 am 12:19 AM

MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.

MySQL's Purpose: Storing and Managing Data EffectivelyMySQL's Purpose: Storing and Managing Data EffectivelyApr 16, 2025 am 12:16 AM

MySQL is an efficient relational database management system suitable for storing and managing data. Its advantages include high-performance queries, flexible transaction processing and rich data types. In practical applications, MySQL is often used in e-commerce platforms, social networks and content management systems, but attention should be paid to performance optimization, data security and scalability.

SQL and MySQL: Understanding the RelationshipSQL and MySQL: Understanding the RelationshipApr 16, 2025 am 12:14 AM

The relationship between SQL and MySQL is the relationship between standard languages ​​and specific implementations. 1.SQL is a standard language used to manage and operate relational databases, allowing data addition, deletion, modification and query. 2.MySQL is a specific database management system that uses SQL as its operating language and provides efficient data storage and management.

Explain the role of InnoDB redo logs and undo logs.Explain the role of InnoDB redo logs and undo logs.Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?What are the key metrics to look for in an EXPLAIN output (type, key, rows, Extra)?Apr 15, 2025 am 12:15 AM

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

What is the Using temporary status in EXPLAIN and how to avoid it?What is the Using temporary status in EXPLAIN and how to avoid it?Apr 15, 2025 am 12:14 AM

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!