好的SQL语句


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
1、说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用)
法一:select * into b from a where 1 <>1
法二:select top 0 * into b from a 

        同用户下别一数据库表的引用为 mydb..mytable   因表与字段之间用一个点表示,故为了区别,数据库与表之间的联系用两个点

2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (Access可用)
insert into b(a, b, c) select d,e,f from b; 

3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (Access可用)
insert into b(a, b, c) select d,e,f from b in ‘具体数据库’ where 条件
例子:..
from b in '"&Server.MapPath(".")&"\data.mdb" &"' where.. 

4,说明:日程安排提前五分钟提醒
SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 

5,说明:随机取出10条数据
select top 10 * from tablename order by newid() 

6、说明:随机选择记录
select newid() 

7,说明:删除重复记录
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)
id 为主键,主键一定不会重复,重复的只是col1,col2 ,按col1,col2分组,相同的分到一组,此时取出最大的id,(min也一样)剩下的就是重复的,去掉即可。
注:dinstinct只能区别一个列值,若想得到唯一的一行记录,可用:
select from tablename where id in( select max(id) from tablename group by col1,col2,... )
select max(id) from tablename group by col1,col2,...  取出表中唯一的行,那么剔除重复,唯一行的个数为:
select count(1) from (select max(id) as id from tablename group by col1,col2,...) m
也可用:select count(1) from (select distinct col1,col2,... from tablename ) m

8、说明:列出数据库里所有的表名
select name from sysobjects where type='U' 

 9,说明:选择从10到15的记录
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc
N到M条记录(要有主索引ID)
Select Top M-N * From 表 Where ID in (Select Top M ID From 表) Order by ID  Desc  

10,按姓氏笔画排序:
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as 

11,查看当前数据库中所有存储过程
select name as 存储过程名称 from sysobjects where xtype='P' 

 12,一条语句执行跨越若干个数据库
select * from OPENDATASOURCE('SQLOLEDB','Data Source=远程ip;User ID=sa;Password=密码').库名.dbo.表名 

13 数据库里有1,2,3,4,5 共5条记录,要用一条sql语句让其排序,使它排列成4,5,1,2,3,怎么写?

select * from t
 order by case id when 4 then 1
                  when 5 then 2
                  when 1 then 3
                  when 2 then 4
                  when 3 then 5 end 

 或:
select * from t order by charindex(cast(id as varchar),'45123')
14,取出一个年级各班的前两名:
class? name? score
2班??? 张二??? 400
2班??? 张三??? 300
2班??? 张四??? 200
2班??? 张五??? 100
3班??? 刘一??? 500
3班??? 刘二??? 400
3班??? 刘三??? 300
3班??? 刘四??? 200
3班??? 刘五??? 100

SELECT t.class,t.name,t.socre
FROM tmp t
WHERE EXISTS( SELECT 1 FROM? (SELECT TOP 2 * FROM tmp tm WHERE tm.class = t.class ORDER BY tm.socre DESC )m WHERE? m.name = t.name )
ORDER BY t.class,t.socre DESC,t.name
--利用子查询获取一个班级内最高的两名然后与总表连接