MSSql数据库sql语句函数大集合

来源:互联网 发布:防御矩阵技能 编辑:程序博客网 时间:2024/06/07 01:10

转自:http://www.721j.com/article/article.asp?id=126 

---------------------------------------

 

聚合函数:

1.AVG 返回组中的平均值,空值将被忽略。
   例如:use  northwind   // 操作northwind数据库
         Go
  Select  avg (unitprice)   //从表中选择求unitprice的平均值
         From  products
         Where  categoryid = ‘8’
2.BINABY_CHECKSUM  可用于检测表中行的更改返回值由表达式的运算结果类型决定
   例如:use northwind
         Go
         Create  table  tablebc(productid int,bchecksum int)   //建立有两个属性的表
         Insert  into tablebc   //向表中插入数据
         Select  priductid,binary_checksum(*)
         From  products
         Update  products   //更新
         Set  productname=’oishi tofu’, unitprice=20 where  productname = ‘tofu’  
         Update  products   //更新
  Set  priductname=’oishi konbu’, unitprice = 5 where priductname=’konbu’
         Update priducts     //更新
         Set  prodctname=’oishi genen shouyu’, unitprice =12
         Where priductname=’genen shouyu’          
   Select  productid    //挑出变化的行
  From tablebc
  Where exists (
         Select productid from products
         Where  product.productid = tablebc.productid and
         binary_checksu (*) <> tablebc.bchecksum)  //标志出变化的行
3.CHECKSUM  返回在表的行上或在表达式上计算的校验值 CHECKSUM 用于生成哈希索引
   例如:
        Set arithabort on
 se northwind
 Go
        Alter table products
        Add cs_pname as checksum(productname)  //在参数列是添加一个校验值
        Create imdex pname_index on products(cs_pname)  //生成索引
        Go
        Select top 5 cs_pname from products order by cs_pname desc //选择根据索引列的前5 个cs_pname
4.Checksum_agg   返回组中值的校验值。空值冽被忽略。
   例如:
        Use northwind
   Go
 Select checksum_agg(cast(unitsinstock  as int)) //检测products 表的unitsinstock列的更改
        from products
5.Count   返回组中项目的数量
   例如:
  例一:
  Use pubs
  Go
  Select count(distinct city)  //对city中的每一行都计算,并返回非空的数量
  From authors
  Go
  例二:
                Use pubs
  Go
  Select count(*)  // 返回组中项目的数量
  From titles
  Go
  例三:
  Use pubs
  Go
  Select count(*),avg(price) // 选择advance大于$1000的总数和平均price
  From titles
  Where advance >$1000
  Go
6.Count_big  返回组中项目的数量。在使用上和count 基本上是一样的,只是在返回值上有一点区别,count_big 返回是bigint的数据类型值,count返回的是int数据类型值。
7.Grouping  返回一个聚合函数,它产生一个附加列,当用CUBE或ROLLUP运算符添加行时,附加 的列输出值为1,当所添加的行不是由CUBE或ROLLUP产生时,附加列值为0
   例如:
  Use pubs
  Go
  Select royalty,sum(advance) ‘total advance’,  //选择列royalty,聚合 advance数值
  Grouping(royalty) ‘grp’  //grouping 函数
  From titles
                Group by royalty with rollup //group by 与 rollup 相联系产生分组
8.Max  返回表达式的最大值
   例如:
  Use pubs
  Go
  Select max(ytd_sales)  //选择ytd_sales列属性,求其最大值。
  From titles
  Go
9.Min  返回表达式的最小值
   例如:
  Use pubs
  Go
  Select min(ytd_sales)  //选择ytd_sales列属性,求其最小值。
  From titles
  Go
10.Stdev  返回给定表达式中所有值的统计标准偏差。
    例如:
  Use pubs
  Select stdev(royalty)
  From titles
11.Stdevp  返回给定表达式中所有值的填充统计标准偏差。
    例如:
  Use pubs
  Select stdev(royalty)
  From titles
12.sum  返回表达式中所有值的的和,或只返回DISTINCT值。SUM只能用数字列。
    例如:
  Use pubs
  Go
  Select type,sum(price),sum(advance)  //选择type,price的和,advance的和
  From titles
  Where type like ‘%cook’  //匹配结尾字符为cook
  Group by type
  Order by type
  Go
    例如2:
  Use pubs
   Go
  Select type,price,advance
  From titles
  Where type like’%cook’
  Order by type
  Compute sum(price),sum(advance) by type   //根据type的属性计算price和advance
的和
13.Var  返回给定表达式中所有值的统计方差。
    例如:
  Use pubs
  Go
  Selecdt var(royalty)
  From titles
14.Varp  返回给定表达式中所有值的填充的统计方差
    例如:
  Use pubs
  Go
  Select  varp(royalty)
  From titles

时间及日期函数


1.Dateadd  在向指定日期加上一段时间的基础上返回新datetime值。
   例如:
  Use northwind
  Go
  Select dateadd(day,3,Hiredate)   //显示函数dateadd执行结果
  From employees
2.datediff  返回跨两个指定日期和时间边界数。
  例如:
  Use northwind
  Go
  Select datediff(day,Hiredate,getdate()) as no_of_days
  From employees
  go
3.Datename  返回代表指定日期的指定日期部分的字符串。
  例如:
 Select datename(month,getdate()) as ‘monthname’
4.Datepart  返回代表指定日期的指定日期部分的整数。
   例如:
  Select datepart(month,getdate()) as ‘monthnumber’
  Select datepart(m,0),datepart(d,0),datepart(yy,0)
5.Day month year  返回指定日期的天 月 年 的日期部分的整数
   例如:
  Select month(0),day(0),year(0)
6.Getdate  按datetime值的标准内部格式返回当前系统时间和日期
   例如:
  Use northwind
  Go
  Create table sales  //创建sales表
  (
  Sale_id char(11) not null  //sale_id列,类型char(11),not null
  Sale_name varchar(40) not null  //sale_name列,类型varchar(40),not null
  Sale_date datetime defaull getdate()  // sale_date列,类型datetime,默认值getdate()
  )
  Insert into sales (sale_id,sale_name)
     Values(1,’foods’)   //向表内插值
  Select * from sales   //表结果检索
7.Getutcdate  返回表当前CUT时间的datetime值。
   例如:
  Select getutcdatea()

数学函数

1.Abs  返回给定数字的绝对值
2.Acos  返回以弧度表示的角度值,该角度值的余弦为给定的float表达式,也叫反余弦
3.Asin   返回以弧度表示的角度值,也叫反正弦。
   例如:
  Declare @angle float
  Set @angle = -1.01
  Select ‘the asin of the angke is : ’ + convert (varchar,asin(@angle))
4.Atan  返回以弧度表示的角度值,该角度值的正切为给定的float表达式,也叫反正切。
5.Atn2  返回以弧度表示的角度值,该角度值的正切介于两个给定的float表达式之间
   例如:
  Declare @anglel float
  Declare @angle2 float
  Set @anglel = 35.175643
  Set @angle2 =129.44
  Select ‘the atn2 of the angle is : ’ + convert (varchar,atn2(@anglel,@angle2))
  Go
6.Ceiling  返回或等于所给数字表达式的最小整数。
   例如:
  Select ceiling($123.45),ceiling($-123.45),ceiling($0.0)
7.Cos  返回给定表达式中给定角度的三角余弦值
8.Cot  返回给定float表达式指定角度的三角余切值
   例如:
  Declare @angle float
  Set @angle = 124.1332
  Select ‘the cot fo the angle is :’ + convert(varchar,cot(@angle))
9.Degrees  当给出弧度为单位的角度时,返回相应的以度数为单位的角度。
   例如:
  Select ‘the number of degrees in PI/2 radinans is :’ +convert(varchar,degrees((PI()/2)))
10.Exp  返回所给的float表达式的指数值。
11.floor  返回小于或等于所给数字表达式的最大整数。
12.log   返回给定float表达式的自然对数。
13.log10  返回给定float表达式的以10为底的对数。
    例如:
  Declare @var float
  Set @var = 5.175643
  Select ‘the log of the variable is :’ +convert (varchar,log(@var))
14.PI  返回PI的常量值。
15.power  返回给定表达式乘指定次方的值。
   例如:
  Declare @value int,@counter int
  Set @value = 2
  Set @counter = 1
  While @counter <5
  Begin
   Select power(@value,@counter)
  Set nocount on
   Set @counter=@counter +1
  End
  Go
16.radians 对于数字表达式中输入的度数值返回弧度值。
17.rand  返回0到1之间的随机float值。
18.round  返回数字表达式并四舍五入为指定的长度或精度。
   例如:
  Select round(123.9995,3),round(123.9994,3)
19.sign  返回给定表达式的正 零 或负号
   例如:
  Declare @angle gloat
  Declare @value real
  Set @value=-1
  While @value<2
   Begin
    Select sign(@value)
  Set nocount on
   Select @value=value+1
   end
  Set nocount off
20.sin 以近似数字表达式返回给定角度的三角正弦值。
21.sqrt  返回给定表达式的平方根。
    例如:
  Declare @myvalue float
  Set @myvalue = 1.00
  While @myvlaue <10
   Begin
    Select sqrt(@myvalue)
  Select @myvalue = @myvalue+1
  End
22.square  返回给定表达式的平方值。
23.tan  返回给定表达式的正切。

元数据函数

1.col_length  返回列的定义长度
例如:
        Use northwind
        Go
        Create table t1
               ( c1 varchar(40),
                C2 nvarchar(80) )
        Go
        Select col_length(‘t1’,’c1’) as ‘varchar’
        Select col_length(‘t2’,’c2’) as ‘nvarchar’
        Go
        Drop table t1
2.col_name  返回数据库列的名称,该列具有相应的表标识号和列标识号。
例如:
        Use northwind
        Go
        Set nocount off
        Select col_name(object_id(‘employees’),1) as employees
3.columnproperty  返回有关列或过程的参数的信息。
例如:
        Use northwind
        Go
        Select columnproperty (object_id(‘employees’),’title’,’precision’)
4.databaseproperty  返回给定数据库和属性名的命名数据库属性值。
例如:
        Use northwind
        Go
               Select databaseproperty(‘northwind’,’isautoclose’)
5.databasepropertyex  返回指定数据库的指定数据库选项或属性的当前设置。
例如:
        Use northwind
        Go         
               Select databasepropertyex(‘northwind’,isautoclose’)
6.db_id  返回数据库标识ID
例如:
        Select name,db_id(name) as db_id
        From sysdatabases
        Order by dbid
7.db_name 返回数据库名称。
8.file_id  返回当前数据库中给定逻辑文件标识(id)号。
9.file_name  返回指定文件标识(id)号的逻辑文件名。
10.filegroup_id  返回给定文件组名称号
11.filegroup_name 返回给定文件组标识(id)号的文件组名。
12.filegroupproperty  给定文件组和属性名时,返回指定的文件组属性值。
13.fileproperty  给定文件名和属性时返回指定的文件名属性值。
14.fn_listextendedproperty  返回数据库对像的扩展属性值。
例如:
        Use northwind
        Go
        Create table t1 (id int, name char(20))  //创建表T1
        Exec sp_addextendedproperty  ‘caption’,’employee id’,’user’,dbo,’table’,’t1’,
’column’,id     //为表T1列ID添加扩展属性
Exec sp_addextendedproperty  ‘caption’,’employee name’,’user’, dbo, ‘table’,
‘t1’,’column’,name
Select * from ::fn_listextendedproperty (null,’suer’,’dbo’,table’,t1’,’column’,
             Default)   //列举表T1的扩展属性
15.fulltextserviceproperty  返回有关全文服务级别属性的信息。
原型:fulltextserviceproperty (catalog_name,property)
        参数说明:
        Catalog_name 包含全文目录名称的表达式。
        Property  包含全文目录属性名称的表达式。
               Property 参数值列表
                      Populatestatus  0 = 空闲  1 = 正在进行完全填充  2 = 已暂停
                                            3 = 中止  4 = 正在恢复   5 = 关机
                                            6 = 正在进行增量填充  7 = 生成索引 
                                            8 = 磁盘已满,已暂停  9 = 更改跟踪
例如:
        Use northwind
        Go  
               Select  fulltextcatalogproperty(‘cat_desc’,’itemcount”)
16.fulltextserviceproperty  返回有关全文服务级别属性的信息。
原型:fulltextserviceproperty(property)
              Property 参数说明

属性

描述

ResourceUsage一个从 1(后台)到 5(专用)之间的值。ConnectTimeout在超时发生前,Microsoft 搜索服务等待所有与 Microsoft® SQL Sever™ 数据库服务器的连接完成以便进行全文索引填充所用的时间(以秒为单位)。IsFulltextInstalled在 SQL Server 的当前实例中安装全文组件。1 = 已安装全文组件。 0 = 未安装全文组件。 NULL = 输入无效或发生错误。DataTimeout在超时发生前,Microsoft 搜索服务等待所有由 Microsoft SQL Server 数据库服务器返回数据以便进行全文索引填充所用的时间(以秒为单位)。

例如:
  Use northwind
  Go
   Select fulltextserviceproperty(‘isfulltextinstalled’)
17. index_col  返回索引列名称。
原型:index_col(‘table’,’index_id’,’key_id’)
  参数:table 表的名称。
     Index_id 索引的ID
     Key_id  键的ID
例如:
  Use northwind
  Go
   Declare @id int, @type char(2), @msg varchar(10), @indid smallint,
@indname sysname, @status int  //声明变量
  Set nocount on
   Select @id=id,@type=type  //获得employees表的ID号以便在系统索引库中
          查找其索引
   From sysobjects
   Where name=’employees’ and type=’u’
   Print ‘index information for the authors table’  //打印输出信息
   Print ‘----------------------------------------------’
  Declare  I cursor   //声明一个游标
   For
   Select indid, name, status  //循环搜索employees 表中所有的索引
   From sysindexes
   Where id=@id
   Open I        //打开游标
   Fetch next from I into @indid, @indname, @status   //获取下一系列索引信息
    If @@fetch_status = 0   //如果状态为0,打印‘ ’
     Print ‘ ‘
      While @@fetch_status = 0  //循环如果从游标处查找还有行,打印出相关
索引信息
    Begin
    Set @msg = null    //初始化变量msg为null
    Set @msg = ‘ index number ‘ + convert(varchar,@indid)+
      ‘is’ + @indname    //填充索引名变量
    Set @indkey = 1    //初始化变量indkey为1
     While @indkey<=16 and index_col(@name,@indid,
@indkey)   // indkey等于key_id,其值可以从1到16
     Is not null
    Begin
    If @indkey = 1  //打印不同的信息当indkey不等于1和等于1时
    Set @msg = msg + ‘, ‘+ Index_col(@name,@indid,@indkey)
     Set @indkey = @indkey + 1   //indkey递增
    End
    Print @msg   //打印信息
    Set @msg = null
    Fetch next from I into @indid,@indname,@status   //循环下一条
   End
   Close I
   Deallocate i
   Set nocount off
18. indexkey_property  返回有关索引键的信息
原型:
  Indexkey_property (table_id,index_id,key_id,property)
  参数说明:
    Table_id 表标识号
    Index_id 索引标识号
    Indkey_id 索引列的位置
    Property  属性的名称,将要为该属性返回信息。
  Propert 的属性参数:
    Columnid 索引的key_id位置上的列ID
    Isdescending 存储索引列的顺序。1=降序,0=升序
例如:
  Use northwind
  Go
   Select indexkey_property(object_id(‘employees’,1,1,’columnid’)
19. indexproperty  在给定表标识号、索引名称及属性的前提下,返回指定的索引属性值
原型:
  Indexproperty (table_id,index,property)
  参数说明:
    Table_id 是包含要为其提供索引属性信息的表或索引视图标识号的表达
式。Table_id的数据类型为int
    Index  一个包含索引的名称的表达式,将为该索引返回属性信息。
    Property 一个表达式,它包含将要返回的数据库属性的名称。
  Property属性的参数:

属性

描述

IndexDepth索引的深度。 返回索引所具有的级别数。IndexFillFactor索引指定自己的填充因子。 返回创建索引或最后重建索引时使用的填充因子。IndexID指定表或索引视图上的索引的索引 ID。IsAutoStatistics索引是由 sp_dboption 的 auto create statistics 选项生成的。 1 = True 0 = False NULL = 无效的输入IsClustered索引是聚集的。 1 = True 0 = False NULL = 无效的输入IsFulltextKey索引是表的全文键。 1 = True 0 = False NULL = 无效的输入IsHypothetical索引是假设的,不能直接用作数据访问路径。假设的索引保留列级统计。 1 = True 0 = False NULL = 无效的输入IsPadIndex索引在每个内部节点上指定将要保持空闲的空间。 1 = True 0 = False NULL = 无效的输入IsPageLockDisallowed1 = 通过 sp_indexoption 禁用页锁定。 0 = 允许页锁定。 NULL = 无效的输入IsRowLockDisallowed1 = 通过 sp_indexoption 禁用行锁定。 0 = 允许行锁定。 NULL = 无效的输入。IsStatistics索引是由 CREATE STATISTICS 语句或由 sp_dboption 的 auto create statistics 选项创建的。对于列级统计,统计索引将用作占位符。 1 = True 0 = False NULL = 无效的输入IsUnique索引是唯一的。 1 = True 0 = False NULL = 无效的输入

例如: 
        Use northwind 
        Go 
            Select indexproperty(object_id(‘categories’),’pk_categories’,’ispadindex’) 
20.    object_id  返回数据库对象标识号。 
原型: 
        Object_id(‘object’) 
例如:     
        Use master 
        Go 
            Select object_id(‘northwind..employees’) 
21.    object_name  返回数据库对象名。 
原型: 
        Object_name(object_id) 
    例如: 
        Use northwind 
        Go 
            Select table_catalog,table_name 
            From information_schema.tables 
            Where table_name = object_name(111770580711) 
22.    objectproperty  返回当前数据库中对象的有关信息。 
原型: 
        Objectproperty(id,property) 
参数说明: 
            Id 一个表达式,包含当前数据库中某一个对象的ID。ID的数据类型为INT。 
            Property 一个表达式,包含针对由ID指定的对象将要返回的信息。  
Property 属性值参数说明:

属性名称

对象类型

描述和返回的值

CnstIsClustKey约束带有聚集索引的主键。 1 = True 0 = FalseCnstIsColumn约束COLUMN 约束。 1 = True 0 = FalseCnstIsDeleteCascade约束带有 ON DELETE CASCADE 选项的外键约束。CnstIsDisabled约束禁用的约束。 1 = True 0 = FalseCnstIsNonclustKey约束带有非聚集索引的主键。 1 = True 0 = FalseCnstIsNotTrusted约束启用约束时未检查现有行,所以可能不是所有行都受约束的控制。 1 = True 0 = FalseCnstIsNotRepl约束使用 NOT FOR REPLICATION 关键字定义约束。CnstIsUpdateCascade约束带有 ON UPDATE CASCADE 选项的外键约束。ExecIsAfterTrigger触发器AFTER 触发器。ExecIsAnsiNullsOn过程、触发器、视图创建时的 ANSI_NULLS 设置。 1 = True 0 = FalseExecIsDeleteTrigger触发器DELETE 触发器。 1 = True 0 = FalseExecIsFirstDeleteTrigger触发器对表执行 DELETE 时触发的第一个触发器。ExecIsFirstInsertTrigger触发器对表执行 INSERT 时触发的第一个触发器。ExecIsFirstUpdateTrigger触发器对表执行 UPDATE 时触发的第一个触发器。ExecIsInsertTrigger触发器INSERT 触发器。 1 = True 0 = FalseExecIsInsteadOfTrigger触发器INSTEAD OF 触发器。ExecIsLastDeleteTrigger触发器对表执行 DELETE 时触发的最后一个触发器。ExecIsLastInsertTrigger触发器对表执行 INSERT 时触发的最后一个触发器。ExecIsLastUpdateTrigger触发器对表执行 UPDATE 时触发的最后一个触发器。ExecIsQuotedIdentOn过程、触发器、视图创建时的 QUOTED_IDENTIFIER 设置。 1 = True 0 = FalseExecIsStartup过程启动过程。 1 = True 0 = FalseExecIsTriggerDisabled触发器禁用的触发器。 1 = True 0 = FalseExecIsUpdateTrigger触发器UPDATE 触发器。 1 = True 0 = FalseHasAfterTrigger表,视图表或视图具有 AFTER 触发器。 1 = True 0 = FalseHasInsertTrigger表,视图表或视图具有 INSERT 触发器。 1 = True 0 = FalseHasInsteadOfTrigger表、视图表或视图具有 INSTEAD OF 触发器。 1 = True 0 = FalseHasUpdateTrigger表、视图表或视图具有 UPDATE 触发器。 1 = True 0 = FalseIsAnsiNullsOn函数、过程、表、触发器、视图指定表的 ANSI NULLS 选项设置为 ON,表示所有与空值的比较都取值为 UNKNOWN。只要表存在,该设置就应用于表定义中的所有表达式,包括计算列和约束。 1 = ON 0 = OFFIsCheckCnst任何CHECK 约束。 1 = True 0 = FalseIsConstraint任何约束。 1 = True 0 = FalseIsDefault任何绑定的默认值。 1 = True 0 = FalseIsDefaultCnst任何DEFAULT 约束。 1 = True 0 = FalseIsDeterministic函数、视图函数的确定性属性。只适用于标量值及表值函数。 1 = 可确定的 0 = 不可确定的 NULL = 不是标量值或表值函数,或者是无效的对象 ID。IsExecuted任何指定执行该对象的方式(视图、过程或触发器)。 1 = True 0 = FalseIsExtendedProc任何扩展过程。 1 = True 0 = FalseIsForeignKey任何FOREIGN KEY 约束。 1 = True 0 = FalseIsIndexed表、视图带有索引的表或视图。IsIndexable表、视图可以创建索引的表或视图。IsInlineFunction函数内嵌函数。 1 = 内嵌函数 0 = 非内嵌函数 NULL = 不是函数,或者是无效的对象 ID。IsMSShipped任何在安装 Microsoft® SQL Server™ 2000 的过程中创建的对象。 1 = True 0 = FalseIsPrimaryKey任何PRIMARY KEY 约束。 1 = True 0 = FalseIsProcedure任何过程。 1 = True 0 = FalseIsQuotedIdentOn函数、过程、表、触发器、视图指定表的被引用标识符设置为 ON,表示在表定义所涉及的所有表达式中,双引号标记分隔标识符。 1 = ON 0 = OFFIsReplProc任何复制过程。 1 = True 0 = FalseIsRule任何绑定的规则。 1 = True 0 = FalseIsScalarFunction函数标量值函数。 1 = 标量值 0 = 表值 NULL = 不是函数,或者是无效的对象 ID。IsSchemaBound函数,视图使用 SCHEMABINDING 创建的架构绑定函数或视图。 1 = 架构绑定 0 = 非架构绑定 NULL = 不是函数或视图,或者是无效的对象 ID。IsSystemTable表系统表。 1 = True 0 = FalseIsTable表表。 1 = True 0 = FalseIsTableFunction函数表值函数。 1 = 表值 0 = 标量值 NULL = 不是函数,或者是无效的对象 ID。IsTrigger任何触发器。 1 = True 0 = FalseIsUniqueCnst任何UNIQUE 约束。 1 = True 0 = FalseIsUserTable表用户定义的表。 1 = True 0 = FalseIsView视图视图。 1 = True 0 = FalseOwnerId任何对象的所有者。 Nonnull = 对象所有者的数据库用户 ID。 NULL = 无效的输入。TableDeleteTrigger表表有 DELETE 触发器。 >1 = 给定类型的第一个触发器的 ID。TableDeleteTriggerCount表表具有指定数目的 DELETE 触发器。 >1 = 给定类型的第一个触发器的 ID。 NULL = 无效的输入。TableFullTextBackgroundUpdateIndexOn表表已启用全文后台更新索引。 1 = True 0 = FalseTableFulltextCatalogId表表的全文索引数据所驻留的全文目录的 ID。 Nonzero = 全文目录 ID,它与标识全文索引表中行的唯一索引相关。 0 = 表不是全文索引的。TableFullTextChangeTrackingOn表表已启用全文更改跟踪。 1 = True 0 = FalseTableFulltextKeyColumn表与某个单列唯一索引相关联的列 ID,这个单列唯一索引参与全文索引定义。 0 = 表不是全文索引的。TableFullTextPopulateStatus表0 = 不填充 1 = 完全填充 2 = 增量填充TableHasActiveFulltextIndex表表具有一个活动的全文索引。 1 = True 0 = FalseTableHasCheckCnst表表具有 CHECK 约束。 1 = True 0 = FalseTableHasClustIndex表表具有聚集索引。 1 = True 0 = FalseTableHasDefaultCnst表表具有 DEFAULT 约束。 1 = True 0 = FalseTableHasDeleteTrigger表表具有 DELETE 触发器。 1 = True 0 = FalseTableHasF, , , oreignKey表表具有 FOREIGN KEY 约束。 1 = True 0 = FalseTableHasForeignRef表表由 FOREIGN KEY 约束引用。 1 = True 0 = FalseTableHasIdentity表表具有标识列。 1 = True 0 = FalseTableHasIndex表表具有一个任何类型的索引。 1 = True 0 = FalseTableHasInsertTrigger表对象具有 Insert 触发器。 1 = True 0 = False NULL = 无效的输入。TableHasNonclustIndex表表具有非聚集索引。 1 = True 0 = FalseTableHasPrimaryKey表表具有主键。 1 = True 0 = FalseTableHasRowGuidCol表对于 uniqueidentifier 列,表具有 ROWGUIDCOL。 1 = True 0 = FalseTableHasTextImage表表具有 text 列。 1 = True 0 = FalseTableHasTimestamp表表具有 timestamp 列。 1 = True 0 = FalseTableHasUniqueCnst表表具有 UNIQUE 约束。 1 = True 0 = FalseTableHasUpdateTrigger表对象具有 Update 触发器。 1 = True 0 = FalseTableInsertTrigger表表具有 INSERT 触发器。 >1 = 给定类型的第一个触发器的 ID。TableInsertTriggerCount表表具有指定数目的 INSERT 触发器。 >1 = 给定类型的第一个触发器的 ID。TableIsFake表表不是真实的。根据需要 SQL Server 对其进行内部具体化。 1 = True 0 = FalseTableIsPinned表驻留表以将其保留在数据高速缓存中。 1 = True 0 = FalseTableTextInRowLimit表text in row 所允许的最大字节数,如果没有设置 text in row 选项则为 0。TableUpdateTrigger表表具有 UPDATE 触发器。 >1 = 给定类型的第一个触发器的 ID。TableUpdateTriggerCount表表具有指定数目的 UPDATE 触发器。 >1 = 给定类型的第一个触发器的 ID。

例如:  
        Select objectproperty(object_id(‘employees’),’tabletextinrowlimit’)          
23.    @@procid  返回当前过程的存储过程标识符(ID)。  
例如:  
        Create procedure  testprocedure  as  //创建存储过程testprocedure    
        Select @@procid as ‘procid’   //列出存储的ID  
        Go  
        Exec testprocedure    //调用存储过程  
        Go  
24.    sql_variant_property  返回有关sql_variant值的基本数据类型的其他信息。  
原型:  
        Sql_variant_property (expression,property)  
        参数说明:  
                Expression  是sql_variant类型的表达式。  
                Property  包含将为其提供信息的sql_variant属性名称。  
    Property的参数说明:

描述

返回的 sql_variant 基本类型

BaseTypeSQL Server 数据类型,如: char int money nchar ntext numeric nvarchar real smalldatetime smallint smallmoney text timestamp tinyint uniqueidentifier varbinary varcharsysname 无效的输入 = NULLPrecision数字基本数据类型的位数: datetime = 23 smalldatetime = 16 float = 53 real = 24 decimal (p,s) and numeric (p,s) = p money = 19 smallmoney = 10 int = 10 smallint = 5 tinyint = 3 bit = 1 all other types = 0int 无效的输入 = NULLScale数字基本数据类型小数点右边的位数: decimal (p,s) 和 numeric (p,s) = s money 和 smallmoney = 4 datetime = 3 所有其它类型 = 0int 无效的输入 = NULLTotalBytes要包含值的元数据和数据所需的字节数。该信息在检查 sql_variant 列中数据的最大一侧时很有用。如果该值大于 900,索引创建将失败。int 无效的输入 = NULLCollation代表特定 sql_variant 值的排序规则。sysname 无效的输入 = NULLMaxLength最大数据类型长度(以字节为单位)。例如,nvarchar(50) 的 MaxLength 是 100,int 的 MaxLength 是 4。int 无效的输入 = NULL例如: 
        Create table tablea (cola sql_variant,colb int)  //创建表tablea 
        Insert into tablea values(cast (462711.1 as decimal(18.2)),16811)  //插入一条记录 
        Select  sql_variant_property(cola,’basetype’),  //检索有关值为462711.1的cola 
                Sql_variant_property(cola,’precision’),  //sql_variant_property信息 
                Sql_variant_property(cola,’scale’)   
        From tablea 
        Where colb=1681 
25.    typeproperty 返回有关数据类型的信息。 
原型: 
        Typeproperty(type,property) 
Property 参数值说明:

属性

描述

返回的值

Precision数据类型的精度。数字位数或字符个数。 NULL = 数据类型未找到。Scale数据类型的小数位数。数据类型的小数位的个数。 NULL = 数据类型不是 numeric 或未找到。AllowsNull数据类型允许空值。1 = True 0 = False NULL = 数据类型未找到。UsesAnsiTrim创建数据类型时 ANSI 填充设置为 ON。1 = True 0 = False NULL = 数据类型未找到,或不是二进制数据类型或字符串数据类型。

例如: 
        Select typeproperty(‘tinyint’,’precision’)

字符串函数
 
1.ascii 返回字符表达式最左端字符的ASCII代码值。
例如:
        Set nocount on
               Declare @position int,@string char(15)
                      Set @position = 1
                      Set @string = ‘du monde entier’
                      While @position <=datalength(@string)
                      Begin 
                      Select 
                      Ascii(substring(@string,@position,1)),
                      Char(Ascii(substring(@string,@position,1)))
                      Set @position =@position+1
                      End
                      Set nocount off
                      Go
2.char  将int ascii代码转换为字符的字符串函数。
3.charindex  返回字符串中指定表达式的起始位置。
原型:
       Charindex(expression1,expression2,[start_location])
       参数说明:
              Expression1 一个表达式,其中包含要寻找的字符的次序。
              Expression2 一个表达式,通常是一个用于指定序列的列。
              [start_logcation] 在expression2中搜索expression1时的起始字符位置。
例如:
       Use pubs
       Go
              Select charindex(‘wonderful’,notes)
                     From titles
              Where title_id=’tc3218’
              Go
在使用[start_logcation]参数时要注意一点。它所能实现的功能是忽略前面的字符,从你给定的字符开始查找expression1在expression2中的位置。
例如:
       declare @t varchar(50)
set @t=’ddfsadawfaafdadfa’
--1
select charindex(’a’,@t,6)
--2
select charindex(’a’,@t,4)
              例1和例2的结果是不一样的。
4.difference  比较两个字符串。
例如:
        Use pubs
        Go
               Select soundex(‘green’)
               Soundex(‘greene’),difference(‘green’,’greene’)
        Go
5.left  返回从字符串左边开始指定个数的字符。
6.len  返回字符串中字符的数量。
7.lower  将大写字符数据转换为小写字符数据后返回字符表达式。
例如:
        Use pubs 
        Go   
        Select lower(substring(tit, le,1,20)) as lower,
                Lower(upper((substring(title,1,20))) as lowerupper
        From titles
        Where price between 11:00 and 20:00
8.ltrim  删除字符串中的起始空格。
9.rtrim  删除字符串中的末尾的空格。
例如:
       Declare @string_to_trim varchar(60)  //声明变量
       Set @string_to_trim = ‘    five spaces are at the beginning of this string’
                                                               //变量赋值
       Select ‘here is the strng without the leading spaces: ’+ ltrim (@string_to_trim)
                                                               //显示函数LTRIM执行结果
10.nchar  根据unicode标准所进行的定义,用给定整数代码返回unicode字符。
例如:
       Declare @position int , @nstring nchar(9)  //声明局部变量
       Set @position = 1    //变量赋值
       Set @nstring = N’k&benhavn’
       Print ‘character #’ + ‘ ’ + ‘unicode character’ + ‘ ‘ + ‘unicode value’ //打印输出 
       While @position <= datalength(@nstring)  //循环判断执行
       Begin 
              Select @position ,    //显示函数nchar执行结果
              Nchar(unicode(substring(@nstring,@position,1))),
              Convert (nchar(17), substring(@nstring,@position,1)),
              Unicode(substring(@nstring,@position,1))
Select @position = @position+1
       End
       Go
11.patindex  返回指定表达式中某模式第一次出现的位置;如果在全部有效的文本和字符
数据类型中没有找到该模式,则返回零。
       例如:
              Use pubs
              Go
              Select patindex(‘%wonderfull%’,notes)
              From totles
              Where totle_id=’tc3218’
              Go
12.quotename  返回带有分隔符的unicode字符串
13.replace  用第三个表达式替换第一个字符串表达式中出现的所有第二个给定字符串
表达式。
       例如:
              Select replace (‘abcdefabcfvabcetil’,’abc’,’xxx’)
14.replicate  以指定的次数重复字符表达式。
15.reverse  返回字符天大的反转。
16.right  返回字符串中从右边开始指定个数的integer_expression字符。
例如:
        Use pubs
        Go
        Select right(au_fname,5)
        From authors
        Order by au_fname
        Go
17.soundex 返回由四个字符组成的代码,以评估两个字符串的相似性。
18.space  返回由重复的空格组成的字符串。也可以向字符串中插入空格。
19.str 由数字数据转换来的字符数据。
原型:
        Str (float_expression [, length,[decimal]])
        参数说明:
               Float_expression 是带有小数点的近似数字数据类型的表达式。
               Length  是总的长度。包括小数点、符号、数字或空格。
               Decimal  是小数点右边的位数。
20.stuff  删除指定长度的字符并在指定的起始点插入另一组字符。
原型:
       Stuff(character_expression,start,length,character_expression)
例如:
       Select stuff(‘abcdefx’,1,2’bckjkjoui’)
21.substring 返回字符,binary,text或image表达式的一部分。
       原型:
              Substring(expression,start,length)
22.unicode 按照unicode标准的定义,返回输入表达式的第一个字符的整数值。
23.upper 返回将小写字符数据转换成大写的字符表达式。

文本和图像函数
 
1.patindex  返回指定表达式中某模式每一次出现的起始位置。详细参阅字符串函数中的patindex。 
2.textptr  以varbinary格式返回对应于text、ntext或image列的文本指针值。 
原型: 
        Textptr(column) 
例如1: 
        Use pubs 
        Go 
        Declare @ptval varbinary(16) 
        Select @ptrval = textptr(logo) 
        From pub_info pr,publishers p 
        Where p.pub_id=pr.pub_id and p.pub_name=’new moon books’ 
        Go 
例如2: 
        Create table t1 (c1 int,c2 text) 
        Exec sp_tableoption ‘t1’,’text in row’,’on’ 
        Insert t1 values(‘1’,’this is text.’) 
        Go 
        Begin tran  
        Declare @ptrval varbinary(16) 
        Select @ptrval = textptr(c2) 
        From t1 where c1=1 
        Readtext t1.c2 @ptrval 0 1 
        Commit 
3.textvald  一个text、ntext或image函数,用于检查给定文本指针是否有效。 
原型:  Textvald(‘table.column’,text_ptr) 
例如: 
        Use pubs 
        Go 
        Select pub_id,’valid (if 1) text data’= textvald(‘pub_info.log’,textptr(logo)) 
        From pub_info 
Order by pub_id 
Go

配置函数
1.connections 返回上次启动sql server 以来连接或试图连接的次数。
2.datefirst  返回set datefirst参数的当前值,setdatefirst参数指明所规定的每周第一天:
1对应星期一,2对应星期二。。。。。7对应星期日。
3.dbts  为当前数据库返回当前timestamp数据类型的值。是数据库中唯一的值。
4.langid  返回当前所使用语言的本地语言标识符(ID)。
5.language  返回当前使用的语言名。
6.lock_timeout  返回当前会话的当前锁超时设置,单位为毫秒。
7.max_connections  批回microsoft sql server 上允许的同时用户连接的最大数。返回的数不必为当前的配置的数值。
8.max_precision  返回decimal 和 numeric数据类型所用的精度级别,即该服务器中当前设置的精度。
9.nestlevel  返回当前存储过程执行的嵌套层次(初始值为0)。
10.options  `返回当前set 选项的信息。
11.remserver  当远程sql server数据库服务器在登录中出现时,返回它的名称。
12.servername 返回运行microsoft sql server 的本地服务器名称。
13.servicename  返回sql server正在运行的实例名。若当前实例为默认实例,则@@servicename返回mssqlserver;否则返回当前实例名。
14.spid  返回当前用户进程的服务器进程标识符(ID)。该结果与当时系统实际运行情况有关。
15.textsize  返回set语句textsize选项的当前值,它指定select语句返回的text 或image数据的最大长度,心字节为单位。
16.service  返回sql server当前安装的日期、版本和处理类型。
例如:
 Use northwind
  Select @@service
上同:

系统函数

1.        app_name  如果应用程序进行了设置,返回当前会话的应用程序名称。
例如:
        Use northwind 
        Go
        Declare @currentapp varchar(35)   //声明局部变量保存函数返回值
        Set @currentapp = app_name()   //调用函数返回当前应用程序的名称
        Select @currentapp  // 显示应用程序的名称
2.        case  计算条件列表并返回多个可能结果表达式之一。
数据原型:
        Case input_expression
               When  when_expression then result_expression
               [….n]
               Else else_result_expression
                     End
3.        cast  将某种数据类型的表达式显式转换为另一种数据类型。
原型:
       Cast (expression as data_type)
4.        convert  将某种数据类型的表达式显式转换为另一种数据类型。
原形:
        Convert (data_type[(length)],expression [,style])
5.        coalesce  返回参数中第一个非空表达式。
例如:
       Use northwind
       Select cast(coalesce(region,companyname) as char) ‘companyregion’
       From suppliers
6.        collationproperty  返回给定排序规则的属性。
原型:
        Collationproperty (collation_name,property)
       例如:
              Use northwind
              Select  collationproperty(‘traditional_spanish_cs_as_ks_ws’,’codepage’)
7.        current_timestamp  返回当前的日期和时间。
8.        current_user  返回当前的用户名。
9.        datalength  返回任何表达式所占用的字节数。
10.    @@error  返回最后执行的transact-sql语句的错误代码。
例如:
        Use northwind 
        Declare @del_error int, @ins_error int  //声明局部变量保存函数返回结果
        Begin tran  //开始一个事务
        Delete shippers  //执行delete操作
        Where shippers=6  
        Select @del_error = @@error   //设置变量保存delete错误操作
        Insert into shippers(shipperid,companyname)  //执行insert操作
        Values(6,’microsoft’)
        Select @ins_error = @@error  设置变量保存insert操作错误
        If @del_error = 0 and @ins_error=0   //测试返回值
        Begin
        Print ‘the author information has been replaced’   //如果以上两个操作全部成功,
则提交事务。
        Commit tran
        End
        Else    //以上两操作失败
        Begin 
               If @del_error<>0    //判断是否delete操作失败
               Print ‘an error occurred during execution of the delete’  //打印输出信息
               If @ins_error <>0   //判断是否insert 操作失败
               Print ‘an error occurred during execution of the insert’  //打印输出信息
        Rollback tran   //事务回滚
        end
11.    fn_helpcollations  //返回sql server 2000支持的所有排序规则的列表。
例如:
       Use northwind
       Select * from ::fn_helpcollations  //显示函数返回的系统所有排序规则列表
12.    fn_serversshareddrives  返回由群集服务器使用共享驱动器名称。
13.    fn_virtualfilestats  返回对数据库文件(包括日志文件)的I/O统计。
原型:
        Fn_virtualfilestats([@databaseid=]databasei_d,[@fileid=] file_id) 
返回的参数说明:

Column Name

数据类型

描述

DbIdsmallint数据库 IDFileIdsmallint文件 IDTimeStampint提取数据的时间NumberReadsbigint在文件上发出的读取次数NumberWritesbigint在文件上写入的次数BytesReadbigint在文件上发出的读取字节数BytesWrittenbigint在文件上写入的字节数IoStallMSbigint用户等待在文件上完成 I/O 活动的总计时间(以毫秒为单位)

例如:
  Use master
  Declare @dbid int
  Select @dbid=dbid from master..sysdatabases
   Where name=’northwind’
  Use northwind
     Select * from ::fn_virtualfilestats(@dbid,1)
14. formatmessage  从sysmessage 现有的消息构造消息。
原型:
  Formatmessage(msg_number,param_value [,….n])
 例如:
  Use master
  Exec sp_addmessage 50001,16,N’the number of rows in %s is %1d’,   //执行存储过
程,增加一条客户信息
  @lang = ‘us_english’
  Use northwind
  Declare @val varchar(100)   //声明变量保存返回值
  Set @val=formatmessage(50001,’table1’,5)  // 构造文本消息
  Select @val
15. getansinull  返回会话的数据库的默认为空性。
原型:
  Getansinull([‘database’])
16. host _id  返回工作站标识号。
17. host_name 返回工作站名称。
原型:
  Host_name()
例如:
  Use northwind
   Select host_name()
18. ident_current  返回任何会话和任何作用域中的指定表最后生成的标识值。
原型:
  Ident_current(‘table_name’)
 例如:
  Use northwind
  Select inde_current(‘shippers’)
19. ident_incr  返回指定表或视图增量值(返回形式为numeric(@@maxpercision,0)),该值
是在带有标识列的表或视图中创建标识列是指定的。
 原型:
  Ident_incr(‘table_or_view’)
 例如:
  Use northwind
  Select ident_incr(‘shippers’)
20. ident_seed  返回指定的表或视图增量值种子值(返回形式numeric(@@maxprcision,0)),
  该值是在带有标识列的表或视图中创建标识列是指定的。
21. @@identity  返回最后插入的标识值。
 例如:
  Use northwind
  Set identity_insert shippers on
  Insert into shippers (shipperid,companyname)
  Values(6,’microsoft’)
  Select @@identity  //显示返回最后插入的标识值
  Delete from shippers where shipperid=6
22 . identity  有在带有into table 子句的select 语句中,以将标识列插入到新表中。
原型:
 Identity(data_type  [, seed,increment])
例如:
 Use northwind
 Select productname, identity(smallint,100,1) as productID,unitprice
 Into test
 From products
 Drop table test
24. isdate  确定输入表达式是否为有效的日期。
原型:
  Isdate(expression)
25. isnull  使用指定的值替换null。
原型:
  Isnull(check_expression,replacement_value)
26. newid  创建uniqueidentifier类型的唯一值。
Declare @myid uniqueidentifiler
Set @myid =newid()
Print ‘value of @myid is : ’+ convert(varchar(255),@myid)
27. nullif  如果两个指定的表达式相等,则返回的是空值;如果不相等则返回第一个表达式。
原型:
  Nullif(expressiion,exprssion)
28. parsename  返回对象的指定部分。
原型:
  Parsename(‘object_name’,object_piece)
参数说明:

Value

描述

1对象名2所有者名称3数据库名称4服务器名称例如:  
Use northwind  
Select parsename(‘pubs..products’,1) as ‘object name’  
Select parsename(‘pubs..products’,2) as ‘object name’  
Select parsename(‘pubs..products’,3) as ‘object name’  
Select parsename(‘pubs..products’,4) as ‘object name’  
29.    permissions  返回一个包含位图的值,表明当前用户的语句、对象或列的权限。  
原型:  
        Permissions([objectid[, ‘column]])  
参数说明:
下表显示语句权限所使用的位(未指定 objectid)。

位(十进制)

位(十六进制)

语句权限

10x1CREATE DATABASE(仅限于 master 数据库)20x2CREATE TABLE40x4CREATE PROCEDURE80x8CREATE VIEW160x10CREATE RULE320x20CREATE DEFAULT640x40BACKUP DATABASE1280x80BACKUP LOG2560x100保留下表显示当仅指定 objectid 时,返回的对象权限所使用的位。

位(十进制)

位(十六进制)

语句权限

10x1SELECT ALL20x2UPDATE ALL40x4REFERENCES ALL80x8INSERT160x10DELETE320x20EXECUTE(仅限于过程)40960x1000SELECT ANY(至少一列)81920x2000UPDATE ANY163840x4000REFERENCES ANY下表显示当同时指定 objectid 和 column 时,返回的列级对象权限所使用的位。

位(十进制)

位(十六进制)

语句权限

10x1SELECT20x2UPDATE40x4REFERENCES例如:
  Use northwind
  If permissions()&2=2
  Begin 
   Print ‘the current user can create a table.’
   Create table test (coll int)
  End
  Else 
   Print ‘error :the current user cannot create a table.’
  Drop table test 
30. @@rowcount  返回受上一语句影响的行数。
例如:
  Use northwind
  Set identity_insert shippers off
  Insert into shippers values(‘ibm’,null)
  Select @@rowcounat
  From shippers 
Delect from shippers where companyname = ‘ibm’
31. rowcount_big  返回受执行的最后一个语句影响的行数。使用和@@rowcount一样。
32. scope_identity  返回插入到同一作用域中的identity列中的最后一个identity值。
33. serverproperty  返回有关服务器实例的属性信息。
34. sessionproperty  返回会话的set 选项设置。
原型:
  Sessionproperty(option) 
Option参数:

选项

描述

ANSI_NULLS指定是否对空值上的等号 (=) 和不等号 (<>)应用遵从 SQL-92 标准行为。 1 = ON 0 = OFFANSI_PADDING控制列存储小于定义的列大小的值的方式,以及列存储在字符串和 binary 数据中有尾随空格的值的方式。 1 = ON 0 = OFFANSI_WARNINGS指定是否对某些情况(包括被零除和算术溢出)生成错误信息或警告应用 SQL-92 标准行为。 1 = ON 0 = OFFARITHABORT确定在执行查询过程中发生溢出或被零除的错误时是否终止查询。 1 = ON 0 = OFFCONCAT_NULL_YIELDS_ NULL控制是将串联结果视为空值还是空字符串值。 1 = ON 0 = OFFNUMERIC_ROUNDABORT指定当表达式中的四舍五入导致精度降低时是否生成错误信息和警告。 1 = ON 0 = OFFQUOTED_IDENTIFIER指定是否遵从 SQL-92 关于使用引号分隔标识符和文字字符串的规则。 1 = ON 0 = OFF<任何其它字符串>NULL = 无效的输入

35. session_user  允许在末指定默认值时,将系统为当前会话的用户名提供的值插入到表
中。还允许在查询、错误信息等中使用用户名。
 例如:
  Use northwind
  Declare @session_usr char(30)
  Set @session_usr = session_user
  Select ‘this session’’ s current user is : ’ + @session_usr
36. stats_date  返回最后一次更新指定索引统计的日期。
例如:
  Use nortywind
  Create index ship_index1 on shippers(shipperid,companyname)
  Waitfor delay ’00:00:20’
  Drop index shippers.ship_index1
  Select ‘index name’=i.name, ‘statisticcs date ’= stats_date(i.id,i.indid)
  From sysobjects o ,sysindexes i
  Where o.name= ‘shippers’ and o.id=i.id
37. system_user  返回登录标识名称。
38. @@trancount  返回当前连接的活动事务数。
39. user_name 返回给定标识号的用户数据库用户名。
例如:use nortywind
  Select user_name(2)
  Select user_name()
  Select name from sysusers where name=user_name(1)

系统统计函数 

1.cpu_busy  返回自上次启动microsoft sql server 以来CUP的工作时间。 
2.idle  返回microsoft sql server 自上次启动后闲置的时间。 
3.io_busy  返回microsoft sql server 自上次启动后用于执行输入和输出操作的时间。 
4.packet_errors  返回microsoft sql server 自上次启动后,在microsoft sql server 连接上发生的网络数据包错误数。 
5.pack_received  返回microsoft sql server 自上次启动后从网络上读取的输入数据包数目 
6.pack_sent  返回sql server自上次启动后,写到网络上的输出数据包数目。 
7.timeticks  返回一刻度的微秒数。 
8.total_errors  返回sql server 自上次启动后,所遇到的磁盘读/写错误数。 
9.total_read  返回microsoft sql server 自上次启动后读取磁盘的次数。 
10.total_write 返回 microsoft sql server 自上次启动后写入磁盘的次数。

事务、游标、存储过程及触发器  

事务的使用:  
1.begin distributed transaction  指定一个事务的起始。  
原型:  
        Begin destributed tran [ saction] [transaction_name! @tran_name_variable]  
例如:  
        Use northwind   
        Begin destributed transaction  //开始一个分布式事务  
        Update empoyees       //对表empolees 进行更新  
        Set firstname=’mcdonald’ where homephone = ‘(206) 555-9875’  
        Commit transaction    //结束事务  
        Go  
2.commit transcation 指明事务结束。  
3.rollback transcation  撒销对数据库作出的所有改变,返回到事务开始之前的状态。  
原型:  
        Rollback [tran [saction] [transaction_name] @tran_name_variable | savepoint_name |  
@savepoint_variable]  
       参数说明:  
        Transadtion 给begin transaction上的事务指派的名称。  
        @tran_name_bariable  用户定义的、含有有效事务名称的变量名称。  
        Savepoint_name  是来自SAVE TRANSACTION语句的svepoint_name。  
        @savepoint_variable 是用户定义的、含有有效保存点名称的变量的名称。  
      例如:  
        Begin transaction royaltychange  //事务开始  
        Update titleauthor  //更新表  
            Set royaltyper = 65   //重设参数  
            From titleauthor,titles   
            Where royaltyper=75   
                And titleauthor.title_id=titles.title_id  
                And title=’The Gourmet Microwave’  
        Update titleauthor  
            Set royaltype = 15  
            From titleauthor, titles  
            Where royaltyper=25  
            And titleauthor.title_id=titles.title_id  
            And title = ‘The Gourmet Microwave’  
        Save transaction percentchanged  //在事务内设置保存点  
        Update titles   
            Set price = price* 1.1  
            Where title =’The Gourmet Microwave’  
        Select (price * royalty * ytd_sales)* royaltyper  
            From titles,titleauthor  
            Where title=’The Gourmet Microwave’  
            And titles.title_id=titleauthor.title_id  
        Rollback transaction percentchanged  //回到先前保存过的保存点  
        Commit transaction   // 事务结束  
4.save transaction  在事务内设置保存点。  
5.commit work  标志事务的结束。  
6.rollback work  将用户的事务回滚到事务的起点。
  
游标的使用:  
1.declare cursor  定义游标结构并分配资源。  
原型:  
    Declate cursor_name [insensitive] [scorll] cursor for select_statement [for { read    
Only | update }[of  column _list]]   
            或者:  
            Declare cursor_name cursor [local | global] [forward_only | scroll] [static | keyset |  
dynamic] [read_only | scroll_locks | optimistic] for [select _statement  
[ for {read only | update } [of column_list]]]  
        参数说明:  
        INSENSITIVE  指明要为检索到的结果集建立一个临时拷贝,以后的数据从这个临时拷贝中获取。原有基表中数据发生了改变,对于游标而言是不可见的。这种不敏感的游标不允许数据更改。  
        SCROLL  指明游标可以在任意方向上滚动。忽略该选项,则游标只能向前滚动。  
        SELECT_SATAEMENT  指明SQL语句建立的结果集。  
        READ ONLY  指明在游标结果集中不允许进行数据更改。  
        UPDATE  指明游标结果集可以进行修改。  
        OF COLUMN_LIST  指明结果集中可以进行修改的列。缺省时(使用UPDATE关键字),所有的列都可进行修改。  
        LOCAL  指明游标是局部的,只能在它所声明的过程中使用。全局的游标在连接激活的任何时候都是可用的。只有池连接结束时,才不再可用。  
        GLOBAL 使用游标对于整个连接全局可见。  
        FORWARD_ONLY  指明游标只能向前滚动。  
        STATIC  与INSENITIVE的游标相同。  
        KEYSET  指明选取的行的顺序。  
        DYNAMIC  指明游标反映所有对结果集的修改。  
        SCROLL_LOCK  对修改或删除加锁。保证游标操作成功。  
        OPTIMISTIC  指明哪些通过游标进行的修改或者删除将不会成功。  
    例如:  
        Use northwind   
        Go   
        Declare customers_cursor cursor    //定义游标  
        For select companyname , address,phone  //选择部分属性  
        From customers   
        Where city=’london’  
        For read only  //只读游标  
        Deallocate customers_cursor   //删除游标  
2.deallocate  删除游标定义,释放资源。  
3.open  打开游标。  
原型:  
    Open { { [global]  cursor_name } | cursor_variable_name }  
    例如:  
        Use northwind   
        Go  
        Declare employee_cursor cursor for   //定义游标  
        Select lastname,firstname   
        From northwind .dbo.employees   
Where firstname like ‘m%’  
Open employee_cursor   // 打开游标  
Fetch next from employee_cursor   //利用游标提取数据  
While @@fetch_status=0   //当利用FETCH提取数据成功时,运用循环提取下一条数据  
Begin   //循环体开始处  
    Fetch next from employee_cursor  
End    //循环体结束  
close employee_cursor    //关闭游标  
Deallocate employee_cursor   // 释放游标  
4.close  关闭游标并释放结果集。  
5.fetch  通过游标从结果集中取值。  
     原型:  
        Fetch [next | prior | first | last | absolute {n | @nvar} | relative {n | @nvar}] from [global]  
             Cursor_name} | cursor_variable_name } [into @variable_name ] [,……n]  
    参数说明:  
        NEXT  指明从当前的行的下一行取值。  
        PRIOR  指明人当前行的前一行取值。  
     &n, bsp;  FIRST  结果集的第一行。  
        LAST   结果集的最后一行。  
        ABSOLUTE  n表示结果集中的第n行。该行数同样可以通过一个局部变量传播。  
        RELATIVE  n表示要取出折行在当前的前n行或后n行的位置上。如果该值为正数则要取出的行在当前行前n行的位置上,如果该值为负数,则返回当前行的后n行。  
        INTO @cursor_variable_name  表示游标列值存储的地方的变量列表。变量的数据类型也应该与被选择列的数据类型相同。直到下一次使用FETCH语句之前,变量中的值都会一直保持。  
    函数返回值:  
        利用@@FETCH_STATUS返回FETCH状态。  
        0:FETCH 成功。  
        1:FETCH 失败或超出设置范围。  
        2:提取的数据行丢失。  
    例如:  
        Open employee_cursor  
        Fetch next from employee_cursor  
        While @@fetch_status = 0   
        Begin   
        Fetch next from employee_cursor  
        End       
        Close employee_curssor
  
存储过程的使用:  
1.create procedure  创建存储过程。  
原型:  
        Create proc [edure] procedure_name [; number]  
        [{@parameter data_type} [varying] [ = default] [output]] [,…n]  
        [ with {recomple | enplication | recompile , encryption }] [for replication]  
        As sql_statement […n]  
    参数说明:  
        Procedure_name  新存储的过程。对于数据库及其所有者必须惟一。创建局部临时过程,在procedure_nameu前加一个编号符#;创建全局临时过程,在procedure_nameu前加两个编号符##。完整的名称不能超过128个字符。  
        Number  对同名的过程分组。  
        @parameter  过程中的参数。  
        Data_type  参数的数据类型。除table之外的其他所有数据类型均可以用伯存储过程的参数。Cursor数据类型只能用于output参数。

 
原创粉丝点击