TSql 从Sql Server 2000到Sql Server 2005

数据库 专栏收录该内容
6 篇文章 0 订阅

微软最新发布的Sql Server 20052000版本进步了不少。最近试用了一下,把两个版本的TSql列出来,方便大家学习。

1.外连接。

Sql Server 2000外连接既可以用outer join,也可以用*= =*2005版只能用outer join,如果执行以下语句

select * from HumanResources.Employee a, HumanResources.EmployeeAddress b
where a.EmployeeID *= b.EmployeeID

系统报错

The query uses non-ANSI outer join operators ("*=" or "=*"). To run this query without modification, please set the compatibility level for current database to 80 or lower, using stored procedure sp_dbcmptlevel. It is strongly recommended to rewrite the query using ANSI outer join operators (LEFT OUTER JOIN, RIGHT OUTER JOIN). In the future versions of SQL Server, non-ANSI join operators will not be supported even in backward-compatibility modes.

2.With

with a as
(
 Select EmployeeID, ContactId from HumanResources.Employee
)
Select * from a

使用with相当于临时的视图,目的是简化代码

3.参数化Top

declare @rowcount int

select @rowcount = 5
select Top(@rowcount) * from HumanResources.Employee

4.Apply

导出表不能跟普通表Join起来,但能够使用Apply去做连接。Apply包括Cross ApplyOuter Apply
Cross Apply:
返回左表和右表都符合条件的数据集
Outer Apply:
无论右表是否有符合条件的数据,左表都至少返回一条数据

以下语句是错误的:

SELECT Product.productNumber, SalesOrderAverage.averageTotal
FROM Production.Product as Product
JOIN ( SELECT AVG(lineTotal) as averageTotal
FROM Sales.SalesOrderDetail as SalesOrderDetail
WHERE product.ProductID=SalesOrderDetail.ProductID
HAVING COUNT(*) > 1
) as SalesOrderAverage

正确的语句:

SELECT Product.productNumber, SalesOrderAverage.averageTotal
FROM Production.Product as Product
CROSS APPLY ( SELECT AVG(lineTotal) as averageTotal
FROM Sales.SalesOrderDetail as SalesOrderDetail
WHERE product.ProductID=SalesOrderDetail.ProductID
HAVING COUNT(*) > 0
) as SalesOrderAverage

5.随机采样数据

 SELECT * FROM sales.salesOrderDetail TABLESAMPLE SYSTEM (2 percent)

从表中随机选取2%的数据。

  • 0
    点赞
  • 1
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值