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