SQL Server(二):T-SQL语言概述

1、T_SQL语言属于SQL语言中的一种:
    SQL结构化查询语言
    所有的数据库编程语言均对ANSI SQL向下兼容,如MS SQL Server的SQL语言、Oracle的PL/SQL语言
2、SQL语言主要包括三类:
    1)DCL——数据控制语言:主要用于控制权限
        Grant:赋权
        Deny:拒绝
        Revoke:恢复初始默认
    2)DDL——数据定义语言:主要用于定义数据库对象
        Create:创建数据库对象
        Alter:修改数据库对象的定义
        Drop:删除数据库对象
    3)DML——数据操纵语言:主要用于操纵数据
        Insert:添加数据
        Update:修改数据
        Delete:删除数据
        Select:查询数据(有一些资料中将Select单独分类为DQL数据查询语言)
3、变量
    在SQL Server中定义变量,变量名前加@(局部变量)或@@(全局变量)
    使用Declare声明变量,使用Set或Select语句为变量赋值。如:
 
 1declare @i int
 2set @i=100
 3
 4declare @sum int
 5select @sum=sum(UnitPrice)
 6from Products
 7
 8declare @price int
 9select @price=UnitPrice
10from Products
11where ProductID=1
12
13declare @singlePrice int
14select @singlePrice=UnitPrice
15from Products
16
17declare @sumPrice int
18set @sumPrice=0
19select @wumPrice=@sumPrice+UnitPrice
20from Products

4、函数
    在SQL Server中函数可以分为以下三类:
    1)标量函数:确定的参数,一个返回值,如常规的函数均属于标量函数。
        
declare @value int
set @value=100
declare @valueString varchar(10)
set @valueString=Convert(varchar(10),@value)
print('Value is '+@valueString)

    2)聚焦函数:参数为一个集合(表中的列),返回为一个值,如数学上的统计函数均属于标量函数。
Select sum(UnitPrice) as [SUM] --取所有单价的和
from Products

Select avg(UnitPrice) as [AVG] --取所有单价的平均值
from Products

Select max(UnitPrice) as [Max] --取所有单价的最大值
from Products

Select min(UnitPrice) as [Min] --取所有单价的最小值
from Products

Select count(Region) as [Count] --取所有Region不为空的行数
from Employees

Select count(*as [Count] --取员工表所有的行数
from Employees

    3)行集函数:参数为确定的参数,返回为一个“结果集”。
select * from 
OpenQuery(
    OracleSvr,  
--打开一个链接服务器
    'SELECT ENAME, EMPNO FROM SCOTT.EMP'  --在链接服务器上执行查询语句
)     --将OpenQuery返回的结果集作为查询的源

5、语句
    1)Begin...End:相当于C、Java、C#中的一对大括号,表示范围限定,没有具体含义,如果其中只有一条语句则可以省略。
    2)While:循环语句
--计算1+2+3++100
declare @i int
declare @sum int
set @i=1
set @sum=0
while @i<=100
    
begin
        
set @sum=@sum+@i
        
set @i=@i+1
    
end
Print(@sum)

    3)If...Else:条件语句
declare @rowCount int
select @rowCount=count(*from SomeTable
if @rowCount=0
    
begin
        
Print('没有数据')
    
end
else if @rowCount>0 and @rowCount<100
    
begin
        
Print('100条以内记录')
    
end
else
    
begin
        
Print('100条以上记录')
    
end

    4)Case语句:属于行级语句(前三种属于语句级),相当于一个函数的作用
Select ProductID,ProductName,UnitPrice,
    
Level=
        
case
            
when UnitPrice<=30 then 'Low Price'
            
when UnitPrice>30 and UnitPrice<=90 then 'Mid Price'
            
else 'High Price'
        
end
from Products
posted @ 2008-01-31 11:39  龙腾于海  阅读(1549)  评论(8编辑  收藏  举报