從一個表中選取數據插入到另一個表中:
select column_name(s) into new_table_name from old_table_name --new_table_name表不必事先存在(復制舊表的架構和數據)
select * into table_new from table_old where 1=2 --只復制舊表架構
insert into Table2(field1,field2,…) select value1,value2,… from Table1 --Table2必須事先存在,並且字段field,field2…也必須存在;
insert into Table2 select * from Table1
identity與select into合用,插入行號:
set identity_insert students on
insert students(id, name, age, city) values(10, 'jim', 18, 'newyank') set identity_insert students off
--注意:一張表中只能有一列為identity,如果指定了自增列,又需要插入指定id的值,需要停止indentiy,執行后再開啟
select identity(int,1,1) as rownumber, name, age, sex, city into students_backup from students --注意:如果查詢的列中有自增列,需要將其刪除,或者屏蔽,因為一張表中只有一個identity字段。
在有identity列的插入時,需要返回當前行的identit的列值:scope_identity()函數
insert into dbo.tb_test2( NAME ) values ( '測試' ) select scope_identity()
返回架構范圍內對象的數據庫對象標識號:object_id()
--查詢表是否存在
select object_id(N'students', N'u') --與以下語句等價
select id from sysobjects where name=N'Students' and type=N'U'
遇到以零做除數錯誤
select (Quantity*Price)/nullif((Quantity*UnitPrice), 0) as[平均值] from ##表 nullif(Expression1, Expression2) --給定兩個參數Expression1和Expression2,如果兩個參數相等,則返回NULL;否則就返回第一個參數。
對已存在表進行操作:
--增加列:
alter table tablename add colum_name datatype --修改列:
alter table dbo.tb_test alter column NAME text
--注:列增加后將不能刪除。DB2中列加上后數據類型也不能改變,唯一能改變的是增加varchar類型的長度。
--添加主鍵:
alter table tabname add primary key(col) --刪除主鍵:
alter table tabname drop primary key(col) --添加唯一約束:
alter table dbo.Students add constraint UK_Stu_Name unique(Name) --刪除唯一約束:
alter table dbo.Students drop constraint UK_Stu_Name
索引、視圖
--創建索引:
create [unique] index idxname on tabname(col….) --unique唯一索引,col1, col2, col3...多個列聯合索引 --刪除索引:
drop index idxname --注:索引是不可更改的,想更改必須刪除重新建。
--創建視圖:
create view viewname as select statement --刪除視圖:
drop view viewname --注:更新視圖暫時沒有直接方法,建議刪除重建
運算符
--union 運算符
union 運算符通過組合其他兩個結果表(例如 table1 和 table2)並消去表中任何重復行而派生出一個結果表。當 all 隨 union一起使用時(即 union all),不消除重復行。兩種情況下,派生表的每一行不是來自 table1 就是來自table2。 --except 運算符
except 運算符通過包括所有在 table1 中但不在 table2 中的行並消除所有重復行而派生出一個結果表。當 all 隨 except 一起使用時 (except all),不消除重復行。 --intersect 運算符
intersect 運算符通過只包括 table1 和 table2 中都有的行並消除所有重復行而派生出一個結果表。當 all 隨 intersect 一起使用時 (intersect all),不消除重復行。
數據庫分頁查詢:
declare @pageSize int --每頁數量
declare @pageIndex int --頁碼
set @pageSize=10
set @pageIndex=5
--適應於SQL Server 2012以下的版本
select top @pageSize id from tb_test2 where id not in (select top (@pageIndex - 1) * @pageSize id from tb_test2) --row_number() over( order by id desc ),該關鍵字只有在SQL Server 2005版本以上才有
select * from (select row_number() over( order by id desc ) as rowNumber, * from tb_test2) temp
where rowNumber > (@pageIndex - 1) * @pageSize and rowNumber <= @pageIndex * @pageSize
--SQL Server 2012以上版本才支持
select * from tb_test2 order by id offset ((@pageIndex - 1) * @pageSize) rows fetch next @pageSize rows only
--選擇從10到15的記錄:
select top 5 * from (select top 15 * from table order by id asc) table_別名 order by id desc
--隨機取出10條數據:
select top 10 * from tablename order by newid()
按姓氏筆畫排序:
select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as --從少到多
查詢各科成績最好的前三名,按課程號升序排列,同課程的成績倒敘排列,加上排名
select CID, SID, Score, Place=(select count(Score) from dbo.SC b where b.CID=a.cid and b.Score>a.score)+1
from dbo.SC a where Score in(select top 3 Score from dbo.SC where CID=a.CID order by Score desc) order by a.CID asc, a.Score desc
結果:

查詢各科的及格率
select CID, convert(varchar(50),100*Pass/(Pass+Fail),2)+'%' as 及格率 from ( select CID, sum(case when Score>=60 then 1 else 0 end) Pass, sum(case when Score<60 then 1 else 0 end) Fail from dbo.SC group by dbo.SC.CID) T1
結果:


查詢“英語”課程第三名的學生的成績單
--查詢所有英語成績(會有並列可能)
select * from dbo.SC where CID=(select CID from dbo.Course where CName='英語') --把成績加入序號,直接獲取序號為3的數據
select * from ( select SID, CID, Score, Place=(select count(distinct(Score)) from dbo.SC b where CID=(select CID from dbo.Course where CName='英語') and b.Score>a.score)+1
from ( select SID, CID, Score from dbo.SC where CID=(select CID from dbo.Course where CName='英語') ) a
)c where c.Place=3
結果:


取出表A中第31到第40記錄(SQLServer,以自動增長的ID作為主鍵,注意:數據不是連續的)
select top 10 * from tableA where ID not in (select top 30 ID from tableA)
team表里只有一個字段name,共有4條紀錄,分別是a,b,c,d,對應四個球隊,現在四個球隊進行比賽,用sql語句顯示所有可能的比賽組合
select * from timp a, timp b where a.name > b.name
有多條重復數據時,只保留一條
delete from Btype_CustomColumns where typeid in (select typeid from Btype_CustomColumns group by typeid having count(typeid) > 1) and dbo.Btype_CustomColumns.ID not in (select min(dbo.Btype_CustomColumns.ID) from Btype_CustomColumns group by typeid having count(typeid)>1)
轉換函數:convert()
說明:一般在時間類型(datetime, smalldatetime)與字符串類型(nchar, nvarchar, char, varchar)相互轉換的時候才用到
tyle數字在轉換時間時的含義如下:
------------------------------------------------------------------------------------------------------------
Style(2位表示年份) | Style(4位表示年份) | 輸入輸出格式
------------------------------------------------------------------------------------------------------------
0 | 100 | mon dd yyyy hh:miAM(或PM)
------------------------------------------------------------------------------------------------------------
1 | 101 美國 | mm/dd/yy
------------------------------------------------------------------------------------------------------------
2 | 102 ANSI | yy-mm-dd
------------------------------------------------------------------------------------------------------------
3 | 103 英法 | dd/mm/yy
------------------------------------------------------------------------------------------------------------
4 | 104 德國 | dd.mm.yy
------------------------------------------------------------------------------------------------------------
5 | 105 意大利 | dd-mm-yy
------------------------------------------------------------------------------------------------------------
6 | 106 | dd mon yy
------------------------------------------------------------------------------------------------------------
7 | 107 | mon dd,yy
------------------------------------------------------------------------------------------------------------
8 | 108 | hh:mm:ss
------------------------------------------------------------------------------------------------------------
9 | 109 | mon dd yyyy hh:mi:ss:mmmmAM(或PM)
------------------------------------------------------------------------------------------------------------
10 | 110 美國 | mm-dd-yy
------------------------------------------------------------------------------------------------------------
11 | 111 日本 | yy/mm/dd
------------------------------------------------------------------------------------------------------------
12 | 112 ISO | yymmdd
------------------------------------------------------------------------------------------------------------
13 | 113 歐洲默認值 | dd mon yyyy hh:mi:ss:mmm(24小時制)
------------------------------------------------------------------------------------------------------------
14 | 114 | hh:mi:ss:mmm(24小時制)
------------------------------------------------------------------------------------------------------------
20 | 120 ODBC 規范 | yyyy-mm-dd hh:mi:ss(24小時制)
------------------------------------------------------------------------------------------------------------
21 | 121 | yyyy-mm-dd hh:mi:ss:mmm(24小時制)
------------------------------------------------------------------------------------------------------------
1、時間轉換為指定形式
select convert(nvarchar(20), getdate(), 120) select convert(nvarchar(100), getdate(), 109) select convert(nvarchar(20), getdate(), 102) select convert(nvarchar(100), getdate(), 113)
結果:

2、轉為XML格式
IF OBJECT_ID('Orders','U') IS NOT NULL
DROP TABLE Orders CREATE TABLE Orders ( ID bigint primary key not null, ProductID int, ProductName nvarchar(50), Price float, Scheme text, Created datetime default(getdate()) ) INSERT INTO Orders(ID,ProductID,ProductName,Price,Scheme) VALUES(201405130001,101,'Card',10.899,'<xml><ProductID>101</ProductID><ProductName>Card</ProductName></xml>')
結果:

存儲過程:
--每次執行都進行重新編譯 --1、存儲過程,重復編譯
IF OBJECT_ID (N'PROC_SELECT_STUDENTS_WITH_RECOMPILE', N'P') IS NOT NULL
DROP procedure PROC_SELECT_STUDENTS_WITH_RECOMPILE; GO
CREATE procedure PROC_SELECT_STUDENTS_WITH_RECOMPILE with recompile --重復編譯
AS
SELECT * FROM Students GO
--加密存儲過程 --2、查詢存儲過程,進行加密
IF OBJECT_ID (N'PROC_SELECT_STUDENTS_WITH_ENCRYPTION', N'P') IS NOT NULL
DROP procedure PROC_SELECT_STUDENTS_WITH_ENCRYPTION; GO
CREATE procedure PROC_SELECT_STUDENTS_WITH_ENCRYPTION with encryption --加密
AS
SELECT * FROM Students GO

set ansi_nulls on
表示對空值(null)對等於(=)或不等於(<>)進行判斷時,遵從 SQL-92 規則。為off時不遵從SQL-92規則
SQL-92規則中,在對空值(null)進行等於(=)或不等於(<>)比較時,取值為false。也就是說:
- 即使是表中字段column_name中包含空值(null),在進行條件判斷 where column_name = NULL 時,該select查詢語句返回的數據是空的/返回零行。
- 即使是表中字段column_name中包含非空值,在進行條件判斷 where column_name <> NULL時,該select查詢語句返回的數據是空的/返回零行。


set quoted_identifier on
on:表示使用 引用標識符,標識符可以用雙引號分隔,但是,文字必須用單引號分隔;off:表示標識符不能用雙引號分隔,否則標識符會被當做字符串值來返回,不再是字符來返回。而且,文字部分必須用單引號或雙引號分隔。

數據庫操作:
--修改數據庫的名稱:
sp_renamedb 'old_name', 'new_name'
--備份數據庫:
backup database ttt to disk = 'F:\BaiduNetdiskDownload\t.bak'
--還原數據庫:
use master restore database test_aa from disk = 'F:\BaiduNetdiskDownload\t.bak'
--分離數據庫:
use master exec sp_detach_db @dbname=N'數據庫名'
--附加數據庫:
exec sp_attach_db @dbname=N'數據庫名',@filename1=N'.mdf的文件路徑',@filename2=N'.ldf的文件路徑'
--列出數據庫里所有的表名:
select name from sysobjects where type='U' --U代表用戶 --列出表里的所有的列名:
select name from syscolumns where id=object_id('TableName')
