--查看指定表的外鍵約束 select * from sysobjects where parent_obj in( select id from sysobjects where name='表名') and xtype='PK' --查看所有表 select * from sysobjects where xtype='PK' --刪除列中含數字的 delete news where patindex('%[0-9]%',title)>0 --刪除刪去 字段 title值重復的行,且只保留 id 較小的這個 delete news where exists(select 1 from news t where t.title=news.title and t.idnews.id) --查看數據庫信息 select * from sys.databases where name='master' 1.按姓氏筆畫排序: Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as 2.分頁SQL語句 select * from(select (row_number() OVER (ORDER BY tab.ID Desc)) as rownum,tab.* from 表名 As tab) As t where rownum between 起始位置 And 結束位置 3.獲取當前數據庫中的所有用戶表 select * from sysobjects where xtype='U' and category=0 4.獲取某一個表的所有字段 select name from syscolumns where id=object_id('表名') 5.查看與某一個表相關的視圖、存儲過程、函數 select a.* from sysobjects a, syscomments b where a.id = b.id and b.text like '%表名%' 6.查看當前數據庫中所有存儲過程 select name as 存儲過程名稱 from sysobjects where xtype='P' 7.查詢用戶創建的所有數據庫 select * from master..sysdatabases D where sid not in(select sid from master..syslogins where name='sa') 或者 select dbid, name AS DB_NAME from master..sysdatabases where sid > 0x01 8.查詢某一個表的字段和數據類型 select column_name,data_type from information_schema.columns where table_name = '表名' 9.使用事務 在使用一些對數據庫表的臨時的SQL語句操作時,可以采用SQL SERVER事務處理,防止對數據操作后發現誤操作問題 開始事務 Begin tran Insert Into TableName Values(…) SQL語句操作不正常,則回滾事務。 回滾事務 Rollback tran SQL語句操作正常,則提交事務,數據提交至數據庫。 提交事務 Commit tran 10. 按全文匹配方式查詢 字段名 LIKE N'%[^a-zA-Z0-9]China[^a-zA-Z0-9]%' OR 字段名 LIKE N'%[^a-zA-Z0-9]China' OR 字段名 LIKE N'China[^a-zA-Z0-9]%' OR 字段名 LIKE N'China 11.計算執行SQL語句查詢時間 declare @d datetime set @d=getdate() select * from SYS_ColumnProperties select [語句執行花費時間(毫秒)]=datediff(ms,@d,getdate()) 12、說明:幾個高級查詢運算詞 A: UNION 運算符 UNION 運算符通過組合其他兩個結果表(例如 TABLE1 和 TABLE2)并消去表中任何重復行而派生出一個結果表。當 ALL 隨 UNION 一起使用時(即 UNION ALL),不消除重復行。兩種情況下,派生表的每一行不是來自 TABLE1 就是來自 TABLE2。 B: EXCEPT 運算符 EXCEPT 運算符通過包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重復行而派生出一個結果表。當 ALL 隨 EXCEPT 一起使用時 (EXCEPT ALL),不消除重復行。 C: INTERSECT 運算符 INTERSECT 運算符通過只包括 TABLE1 和 TABLE2 中都有的行并消除所有重復行而派生出一個結果表。當 ALL 隨 INTERSECT 一起使用時 (INTERSECT ALL),不消除重復行。