Home Database Mysql Tutorial SqlServer 2005 T-SQL Query 学习笔记(1)

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

Jun 07, 2016 pm 06:05 PM
sqlserver

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

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

OrderDateOrderYearCustomerIDNumCusts
dboOrders
OrderYear
Copy after login

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

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

OrderYearCustomerIDNumCusts
OrderDateOrderYearCustomerID
   dboOrdersD
OrderYear
Copy after login

还有一种很特殊的写法:

OrderYearCustomerIDNumCusts
OrderDateCustomerID
   dboOrders<u>D<strong>OrderYearCustomerID</strong></u>OrderYear
Copy after login

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

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

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

多重引用,有可能你的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
Copy after login

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

COrderYearCustomerIDOrderDateCustomerID
 dboOrders
OrderYearCustomerIDNumCusts
C
OrderYear
Copy after login

CTE实例二(多重CTEs)

C1 OrderDateOrderYearCustomerID
 dboOrders
C2 OrderYearCustomerIDNumCusts
 C1
 OrderYear
OrderYearNumCusts
C2
NumCusts 70
Copy after login

CTE实例三(多重引用)

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

CTE实例四(修改数据)

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

dboCustomersDupsGO

CrossCustomers 1 cC1dboCustomers C1dboCustomers C2
cKeyColCustomerIDCompanyNameContactNameContactTitleCityRegionPostalCodeCountryPhoneFax
dboCustomersDups
CrossCustomers
Copy after login

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

JustDups dboCustomersDups C1
 KeyCol KeyColdboCustomersDups C2
   C2CustomerID C1CustomerIDJustDups
Copy after login

CTE实例五(对象容器)

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

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

有个例子,如下:

dboVYearCnt
YearCnt OrderDateOrderYearCustomerIDNumCusts
 dboOrders
 OrderDateYearCnt
Copy after login

CTE实例六(CTEs的递归)

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

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

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

idx_mgr_emp_ifname_ilname
 dboEmployeesReportsToEmployeeIDFirstNameLastName
Copy after login

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

小知识:什么Include索引?

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

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

EmpsCTE EmployeeIDReportsToFirstNameLastName
 dboEmployees
 EmployeeID 5
 EMPEmployeeIDEMPReportsToEMPFirstNameEMPLastName
 EmpsCTE MGR
  dboEmployees EMP
   EMPReportsTo MGREmployeeID
EmpsCTE
Copy after login

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

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

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

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

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to import mdf file into sqlserver How to import mdf file into sqlserver Apr 08, 2024 am 11:41 AM

The import steps are as follows: Copy the MDF file to SQL Server's data directory (usually C:\Program Files\Microsoft SQL Server\MSSQL\DATA). In SQL Server Management Studio (SSMS), open the database and select Attach. Click the Add button and select the MDF file. Confirm the database name and click the OK button.

How to solve the problem that the object named already exists in the sqlserver database How to solve the problem that the object named already exists in the sqlserver database Apr 05, 2024 pm 09:42 PM

For objects with the same name that already exist in the SQL Server database, the following steps need to be taken: Confirm the object type (table, view, stored procedure). IF NOT EXISTS can be used to skip creation if the object is empty. If the object has data, use a different name or modify the structure. Use DROP to delete existing objects (use caution, backup recommended). Check for schema changes to make sure there are no references to deleted or renamed objects.

What to do if the sqlserver service cannot be started What to do if the sqlserver service cannot be started Apr 05, 2024 pm 10:00 PM

When the SQL Server service fails to start, here are some steps to resolve: Check the error log to determine the root cause. Make sure the service account has permission to start the service. Check whether dependency services are running. Disable antivirus software. Repair SQL Server installation. If the repair does not work, reinstall SQL Server.

How to check sqlserver port number How to check sqlserver port number Apr 05, 2024 pm 09:57 PM

To view the SQL Server port number: Open SSMS and connect to the server. Find the server name in Object Explorer, right-click it and select Properties. In the Connection tab, view the TCP Port field.

How to recover accidentally deleted database in sqlserver How to recover accidentally deleted database in sqlserver Apr 05, 2024 pm 10:39 PM

If you accidentally delete a SQL Server database, you can take the following steps to recover: stop database activity; back up log files; check database logs; recovery options: restore from backup; restore from transaction log; use DBCC CHECKDB; use third-party tools. Please back up your database regularly and enable transaction logging to prevent data loss.

Where is the sqlserver database? Where is the sqlserver database? Apr 05, 2024 pm 08:21 PM

SQL Server database files are usually stored in the following default location: Windows: C:\Program Files\Microsoft SQL Server\MSSQL\DATALinux: /var/opt/mssql/data The database file location can be customized by modifying the database file path setting.

How to solve Java connection SqlServer error How to solve Java connection SqlServer error May 01, 2023 am 09:22 AM

The problem was found that this time I was using the SqlServer database, which I had not used before, but the problem was not serious. After I connected the SqlServer according to the steps in the requirements document, I started the SpringBoot project and found an error, as follows: At first I thought it was a SqlServer connection. There was a problem, so I went to check the database and found that everything was normal. I first asked my colleagues if they had such a problem, and found that they did not, so I started my best part, facing Baidu. programming. The specific error message I started to solve was this, so I started Baidu error reporting: ERRORc.a.d.p.DruidDataSource$CreateCo

How to delete sqlserver if the installation fails? How to delete sqlserver if the installation fails? Apr 05, 2024 pm 11:27 PM

If the SQL Server installation fails, you can clean it up by following these steps: Uninstall SQL Server Delete registry keys Delete files and folders Restart the computer

See all articles