SQL查询语句

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 表名) ; 



  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值