SQL查询语句

来源:互联网 发布:单词社交网络高级版pdf 编辑:程序博客网 时间:2024/06/06 20:04

1、查询表中的所有字段名和字段数

查询表中所有的字段名称
select name from syscolumns where id = object_id('表名');
查询表中的字段数
select count(name) from syscolumns where id = object_id('表名');

规范一些就改成 object_id(N'表名'),一般不会出错
select name from syscolumns where id=object_id(N'表名');  --列名
select name from sysobjects where xtype = 'U';            --表名
select name from sysobjects where xtype = 'P';            --存储过程

2、升序降序

ORDER BY  ...  ASC      -- 升序

ORDER BY  ...  DESC      -- 降序

3、查询时间段

select * from 表名 where 字段名  between '2015-09-01' and '2015-09-11';

select * from 表名 where 字段名 >= '2015-09-01' and 字段名 <= 2015-09-11'';

select * from 表名 where 字段名 >= '2015-09-01' and 字段名 <= 2015-09-11 23:59:59'';

select * from 表名 where 字段名 > '2015-09-01';

select * from 表名 where 字段名 < '2015-09-11';

4、查询具体某一列

select 字段名 from 表名;

5、修改语句

update 表名 set 字段名='要修改的内容' where 字段名='字段值';

6、指定某一行为第一行,其他按年份排序

select * from 表名 order by (case when 字段名 '字段值' then 0 else 1 end), 字段名 DESC;

7、多表查询

select 替代的字母1.字段名,替代的字母1.字段名 from "表名1替代的字母1 join "表名2替代的字母2 on 替代的字母1.字段名替代的字母2.字段名 where 替代的字母2.字段名='字段名内容';

select 替代的字母1.字段名 ,替代的字母2.字段名 from "表名1替代的字母1, "表名2替代的字母2 where 替代的字母1.字段名替代的字母2.字段名 order by 替代的字母2.字段名 ;

8、排除重复

select distinct 字段 from 表名;

9、查询日期最大的一条记录

select * from 表名 替代的字母 where not exists(select 1 from 表名 where 字段>替代的字母.字段);

select * from 表名 替代的字母 where not exists(select 1 from 表名 where 字段=替代的字母.字段 and 字段>替代的字母.字段);

例:select * from table_Name t where not exists(select 1 from table_Name where 编号=t.编号 and 日期>t.日期)

10、查询结果增加自动递增序列号

select row_number()over(order by 字段名 ASC) AS Id,* from 表名;

select identity(int,1,1) as Id,* into 新表名 from 表名 Select * from 表名 Drop table 表名;

select (select SUM(1)from 表名 where 主键 <= a.主键) AS Id,*from 表名 a;

select (select COUNT(1)from 表名 where 主键 <= a.主键) AS Id,*from 表名 a;

11、取出表A中第31到第40记录(SQLServer,以自动增长的ID作为主键,注意:ID可能不是连续的。
select top 10 * from 表名 where id not in (select top 30 id from 表名);
select top 10 * from 表名 where id > (select max(id) from (select top 30 id from 表名 )as 表名) ; 



0 0
原创粉丝点击