无忧岛

28 九, 2009

SQL常用语句之字段名查询/建索引/增加字段/区间记录集查询

Posted by: kinglife In: SQL Server

导读:关于SQL SERVER的常用维护/查询/优化等在之前有写过一些SQL Server查询优化方案整理SQL触发器教程以及一些常用的行列转换等sql语句

今天再次整理下最近用到的SQL语句:指定表的字段名查询/索引的建立/增加字段/区间记录的SQL查询语句.

  • 1.查询指定表中含有哪些字段?
  • 
    select name from syscolumns where id in (select id from sysobjects where type = 'u' and name = '表名')  
    
  • 建索引脚本:
  • 
    create clustered index 索引名 on 表名(表.字段)
    
  • 在表增加一个字段名为CName,数据类型为Int,不可为空,默认值是0的字段
  • 
    alter table 表名 add CName int not null default 0
    
  • TOP 10是取前十个查询结果,现在需要取查询结果的区间数据 X至Y条数据的语句,例如选择前面第 X-Y条记录的sql语句如下:
  • 
    --注意文中的testt为你的表名,另注意你的表中应该有一个自增字段 ID
    declare @X int,@Y int,@M int,@N int	--X:起始位置  Y:终止位置
    set @X=5	--初始化变量 开始
    set @Y=10	--初始化变量 结束
    set @M=@Y-@X+1
    set @N=@X-1
    
    --正序
    execute ('select top '+ @M +' * from testt
    where id not in (select top '+ @N +' id from testt)')
    
    --倒序
    execute ('select top '+ @M +' * from testt
    where id not in (select top '+ @N +' id from testt order by id desc) order by id desc')
    

    版权所有,转载时必须以链接形式注明作者和原始出处及本声明:KingLife@无忧岛

    本文链接: http://www.islandcn.com/post/707.html



    No Responses to "SQL常用语句之字段名查询/建索引/增加字段/区间记录集查询"

    Comment Form

    Categories

    Flickr PhotoStream

      flickrRSS probably needs to be setup

    About

    Name:KingLife
    Email:lifewz#163.com