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
--利用子查詢獲取一個班級內最高的兩名然後與總表連接