Dzwebs.Net

撰写电脑技术杂文十余年

SQL常用的精典语句

Admin | 2007-11-19 12:49:48 | 被阅次数 | 7043

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

1:说明:复制表(只复制结构,源表名:a 新表名:b) (Access可用)
方法一:select * into b from a where 1<>1
方法二:select top 0 * into b from a
注意:复制的新表中的所有字段都将没有默认值,即使源表中有设默认值

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


3:说明:显示文章、提交人和最后回复时间
select a.title,a.username,b.adddate from a,(select max(adddate) adddate from table,a where table.title=a.title) b


4:说明:两张关联表,删除主表中在副表中没有的信息
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )
注意:
若将
select * from table2 where table1.field1=table2.field1
改为
select * from table1,table2 where table1.field1=table2.field1
多了一个table1
则删除不成功

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

说明:一条sql 语句搞定数据库分页
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段

6:说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.)
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)


7:说明:包括所有在 TableA 中但不在 TableB和TableC 中的行并消除所有重复行而派生出一个结果表
(select a from tableA ) except (select a from tableB) except (select a from tableC)


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


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


10:说明:删除重复记录
Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)


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


12:说明:列出表里的所有的
select name from syscolumns where id=object_id('TableName')
使用SQL语句 用...代替过长的字符串显示
语法:
SQL数据库:select case when len(field)>10 then left(field,10)+'...' else field end as news_name,news_id from tablename
Access数据库:SELECT iif(len(field)>2,left(field,2)+'...',field) FROM tablename;
--获得当月最后一天,时间全是0,如:2007-09-30 00:00:00.000
select dateadd(dd,-1,dateadd(mm,datediff(mm,0,dateadd(mm,1,getdate())),0))
--获得当月最后一天,时间为当前时间,如:2007-09-30 12:07:37.030
select dateadd(dd,-1,dateadd(mm,1,getdate()-day(getdate())+1))
--获得当月天数,如:30
select datediff(dd,getdate()-day(getdate())+1,dateadd(mm,1,getdate()-day(getdate())+1))

 


该杂文来自: 数据库Sql,VFP,Access

上一篇:SQL2005使用NTILE和ROW_NUMER为查询实现分页

下一篇:SQL存储过程的介绍及简单的存储过程介绍

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计