創建文件夾:exec xp_cmdshell 'md 盤符:/文件夾名稱', no_output
例如:在D盤創建名爲:“資料”的文件夾:exec xp_cmdshell 'md d:/資料', no_output
查看文件:exec xp_cmdshell 'dir盤符:/文件夾名稱'。例如:exec xp_cmdshell 'dir d:/資料'
判斷數據庫是否存在:if exists(select * from sysdatabases where name='數據庫名稱')
drop database 數據庫名稱
判斷表是否存在——if exists(select * from sysobjects where name='表名') drop table 表名
添加約束(5種)——語法:alter table 表名 add constraint 約束名約束類型 具體的約束說明
1.主鍵約束:alter table 表名 add constraint pk_約束名 primary key(主鍵約束字段名)
2.外鍵:alter table表名add constraint fk_約束名foreign key(外鍵字段名) references 關係表(主鍵名)
3.唯一約束:alter table 表名 add constraint uq_約束名 unique (唯一約束字段名)
4.檢查約束:alter table 表名 add constraint ck_約束名 check (約束檢查字段名) --表達式
5.默認約束:alter table 表名 add constraint df_約束名 default (默認值) for 默認約束字段名
刪除約束語法:alter table 表名 drop constraint 約束名
例如:刪除stuInfo表中地址的默認約束:alter table stuInfo drop constraint 約束名(df_stuAddress)
第一道大門——創建登錄帳戶(2種)
第一種:SQL賬戶:exec sp_addlogin '用戶名','密碼'
第二種:Windows賬戶:exec sp_grantlogin 'windows域名/域賬戶'
第二道大門——創建數據庫用戶 :exec sp_grantdbaccess '登錄賬戶','數據庫用戶'
--“數據庫用戶”爲可選參數,默認爲登錄賬戶,即數據庫用戶默認和登錄賬戶同名。
例如:在數據庫中添加一個用戶:
exec sp_grantdbaccess 'zhang','zhangUser' --'zhang爲登錄賬戶','zhangUser爲數據庫用戶'
第三道大門——向數據庫用戶授權:grant 權限 on 表名 to 數據庫用戶
例如:爲zhangsanUser授予對錶stuInfo的增刪該查的權限
grant select,update,delete,insert on stuInfo to zhangsanUser
建表的權限:grant create table to zhangsanUser
----------------------------------第三章 T—SQL編程----------------------------------
聲明局部變量,語法:declare @局部變量名 數據類型 例如:declare @sum int
變量賦值,方法(2種)
第一種:使用set語句:set @變量名=值 例如:set @sum=1
第二種:使用select語句:select @變量名=值 例如:select @sum=1
全局變量:注意:有兩個@@
@@error --錯誤號 @@identity --最後一次插入的標識值
@@language --當前使用的語言名稱 @@max_connections --可以創建的同時連接的最大數目
@@rowcount --受上一個SQL語句影響的行數 @@servername --本地服務器的名稱
@@servicename --該計算機上的SQL服務的名稱 @@timeticks --當前計算機上每刻度的微秒數
@@trancount --當前連接打開的事務數 @@version --SQL server的版本信息
輸出語句
第一種方法:print 局部變量或字符串——例如:print '服務器名稱:'+convert(varchar(20),@@servername)
第二種方法:select 局部變量 as 自定義別名 --例如:select @@servername as 服務器名稱
邏輯控制語句
1.if_eles語句 if(條件) begin 語句或語句塊 end else begin 語句或語句塊 end |
2.while語句 while(條件) --注意:“1=1”爲條件永遠成立 begin 語句或語句塊 break end |
3.case多分支語句 case when 條件1 then 結果1 when 條件2 then 結果2 else 其他結果 end |
批處理語句可提高語句的執行效率,結束的標誌爲:go
---------------------------------------第四章 高級查詢---------------------------------------
一般來說,表連接都可以用子查詢替換,但子查詢不一定能用表連接來替換
子查詢返回的值只有一個,可以用“=,!=,>,>=,<,<=”
in 和not in 子查詢——子查詢的返回值多於一個
--例如:
select stuName(表中字段) from stuInfo (表名) where stuNo(表中字段) in (select stuNo(表中字段) from stuMarks(表名))
select stuName(表中字段) from stuInfo(表名) where stuNo(表中字段) not in(select stuNo(表中字段) from stuMarks(表名))
exists和 not exists子查詢——存在檢測的子查詢語句
基本語法:if exists 或 not exists(子查詢) 語句
表聯接:1.內聯接(inner join) 2.左外聯接(left outer join) 3.右外聯接(right outer join)
4.完全外聯接(full outer join)
5.自聯接(inner join)(同一個表)
select * from 表名1 別名1 inner join 表名1 別名2 on 別名1.公共字段=別名2.公共字段
表聯接查詢:select 字段名 from 表1 inner join 表2 on 表1.公共字段=表2.公共字段
表聯接更新:
update 表1 set 表1的字段名更新 from 表1 inner join 表2 on 表1.公共字段=表2.公共字段
生成表查詢:select * into 生成表名 from 原來的表 例:select * into stuInfo1 from stuInfo
向生成表中插入數據:insert into 生成表名 select * from 原來的表
----------------------------------第五章 事務、索引、視圖--------------------------------
事務——是單個的工作單元,一組數據庫操作命令,同時成功、同時失敗。
開始事務:begin transaction(tran)以作爲事務的開始
提交事務:commit transaction(tran)
回滾(撤銷)事務:rollback transaction(tran)
事務中須設置,累計錯誤變量,用於累計是否有錯誤。即:
declare @errorSum int --定義累計錯誤變量
set @errorSum=0 --設初值爲0,即無錯誤
set @errorSum=@errorSum+@@error --錯誤累計
判斷
if(@errorSum<>0) --表明有錯誤
begin
print '有錯誤,事務回滾'
rollback tran
end
else
begin
print '無錯誤,提交成功'
commit tran
end
索引——提高查詢速度
創建索引的語法:create 索引類型 index 索引名 on 表名 (字段名) with fillfactor=數值
索引類型包括:
1.unique(唯一索引)。
2.clustered(聚集索引),一個表中只能有一個。表中各行的物理順序與鍵值的邏輯(索引)順序相同。
3.nonclustered(非聚集索引),可以有多個,最多249個。表中各行的物理順序與鍵值的邏輯順序不相同。
fillfactor爲填充因子:0—100之間的值,該值指示索引頁填滿的空間所佔的百分比。
刪除索引——drop index 表名.索引名
視圖——一種虛擬表,不是數據庫中存儲的數據值的集合,而是實際表中各個字段的位置
判斷視圖是否存在——if exists(select * from sysobjects where name='view_視圖名')
drop view view_視圖名
創建視圖——create view view_視圖名 as <select 語句>
查詢視圖——select * from view_視圖名
-----------------------------------第六章 存儲過程--------------------------------------
存儲過程——是SQL語句和控制流語句的預編譯集合,減少網絡流量,提高訪問速度。
常用的系統存儲過程
1.exec sp_databases --列出當前系統中的數據庫
2.exec sp_renamedb '原來的數據庫名','改後新數據庫名' --更改數據庫名稱(單用戶訪問)
exec sp_rename '原來名','改後新名' --更改對象名稱(單用戶訪問)對象可爲:表、視圖、存儲過程等
例如:
exec sp_rename '原來的表名','改後新表名' --更改表名稱(單用戶訪問)
exec sp_rename '原來的視圖名','改後新視圖名' --更改視圖名稱(單用戶訪問)
3.exec sp_tables --當前數據庫中可查詢對象的列表
4.exec sp_columns 表名 --查表中列的信息 例如:exec sp_columns stuInfo--查表stuInfo中列的信息
5.exec sp_help 表名 --查看錶的信息; 例如:exec sp_help stuInfo --查看錶stuInfo的信息
6.exec sp_helpconstraint 表名 --查表的約束
例如:exec sp_helpconstraint stuInfo --查表stuInfo的約束
7.exec sp_helpindex 表名 --查看錶的索引; 例如:exec sp_helpindex stuInfo --查看錶stuInfo的索引
8.exec sp_helptext 視圖名 --查看視圖的語句文本
9.exec sp_stored_procedures --返回當前數據庫中的存儲過程列表
10.exec sp_helpdb 數據庫名 --報告有關指定數據庫或所有數據庫的信息
例如:exec sp_helpdb --所有數據庫; exec sp_helpdb Tours --指定數據庫Tours
11.exec xp_logininfo --查看當前登錄信息
12.exec sp_pkeys 表名 --查看錶的主鍵信息
判斷存儲過程是否存在——if exists(select * from sysobjects where name='proc_存儲過程名')
drop proc proc_存儲過程名
創建存儲過程(兩種) --輸出參數須註明output
第一種:(不帶參數) create proc proc_存儲過程名 as SQL語句 調用存儲過程——exec 存儲過程名 |
第二種:(帶參數) create proc proc_存儲過程名 @參數1 數據類型 [=默認值] [output] @參數n 數據類型 [=默認值] [output] as SQL語句 調用存儲過程——exec 存儲過程名 [參數]output |
處理錯誤信息——raiserror('提示信息',錯誤級別,錯誤狀態) --例如:raiserror('提示信息',16,1)
------------------------------第七章 觸發器---------------------------------
觸發器——是在對錶進行插入、更新、刪除操作時自動執行的存儲過程。包括三個觸發器:
1.insert觸發器:向表中插入數據時觸發,自動執行觸發器所定義的SQL語句。
2.update觸發器:更新表中某列、多列數據時觸發,自動執行觸發器所定義的SQL語句。
3.delete觸發器:刪除表中數據時觸發,自動執行觸發器所定義的SQL語句。
檢測觸發器是否存在——if exists(select name from sysobjects where name='trig_觸發器名')
drop trigger trig_觸發器名
創建觸發器
create trigger trig_觸發器名
on 表名
[with encryption]加密 --可省略
for 觸發器[insert,update,delete] --可多選,中間用“,”分隔
as
SQL語句
注意:應用delete觸發器時,要應用備份表
判斷備份表是否存在(不存在則創建,存在則將數據插入到備份表中)
if not exists(select name from sysobjects where name='備份表')
創建備份表
select * into 備份表 from deleted --從deleted表中獲取被刪除的數據
else
將被刪除的數據插入到備份表中
insert into 備份表 select * from deleted
創建一個數據庫(庫名:學生庫)並設置兩個數據文件和兩個日誌文件
create database 學生庫
on primary
( name=學生_data1, filename='e:/學生_data1.mdf', size=1mb, maxsize=3mb,filegrowth=1mb ),
( name=學生_data2, filename='e:/學生_data2.ndf', size=1mb, maxsize=3mb, filegrowth=10% )
log on
( name=學生_log1, filename='e:/學生_log1.ldf', size=1mb, maxsize=2mb, filegrowth=1mb ),
( name=學生_log2, filename='e:/學生_log2.ldf', size=1mb, maxsize=2mb, filegrowth=10% )
刪除數據庫:drop database 學生庫(數據庫名)
更改數據庫中(數據文件學生_data1)的原始大小結構
alter database 學生庫 modify file ( name=學生_data1,size=5mb )
更改數據庫中(日誌文件學生_log1)的原始大小結構
alter database 學生庫 modify file ( name=學生_log1,size=2mb )
爲數據庫添加一個日誌文件(學生_log3)
alter database 學生庫
add file( name=學生_log3, filename='e:/學生_log3.ldf', size=1mb,maxsize=2mb, filegrowth=10% )
設置數據庫(學生庫)爲只讀:exec sp_dboption '學生庫','read only',true
設置在同一時間內只有一個用戶訪問數據庫(學生庫):exec sp_dboption '學生庫','single user'
自定義數據類型:exec sp_addtype city(類型名) ,'nvarchar(15)',null
刪除自定義數據類型:exec sp_droptype city(類型名)
use 學生庫 打開數據庫(學生庫)
create table 學生表(表名) 創建一個學生表
( 學號 int not null, 姓名 varchar(20), 愛好 varchar(20), 出生日期 datetime)
刪除表:drop table 學生表(表名)
標識約束屬性(兩種方法):
①在創建表(學生表)的同時,將學號設置標識
create table 學生表
(學號int not null identity(1,1)primary key,姓名varchar(20)unique,愛好varchar(20),出生日期 datetime)
②更改學生表,添加學號標識
create table 學生表(姓名 varchar(20) unique,愛好 varchar(20),出生日期 datetime)
alter table 學生表 add 學號(字段名) int identity(1,1)
主鍵約束(兩種方法):
①在創建表(學生表)的同時,將學號設置主鍵
create table學生表(學號int not null primary key,姓名char(20),愛好char(20),出生日期datetime)
②更改學生表,將學號設爲主鍵:alter table 學生表 add constraint pk_學號 primary key (學號)
唯一約束(兩種方法):
①更改學生表,將姓名設爲唯一約束:alter table 學生表 add constraint uq_姓名 unique (姓名)
②在創建表(學生表)的同時,將姓名設置唯一約束
create table學生表(學號int not null primary key,姓名char(20)unique,愛好char(20),出生日期 datetime)
外鍵約束(兩種方法):
①創建一個成績表,學號字段設置外鍵,引用學生表表中的學號字段
create table 成績表(學號int foreign key references 學生表(學號),姓名char(20),科目char(20),成績 int)
②更改成績表,外鍵,將引用“學生表”中的“學號”:
alter table 成績表 add constraint fk_學號 foreign key 學號references 學生表(學號)
檢查約束(兩種方法):
①更改成績表,添加檢查約束,將查找成績在0—100之間
alter table 成績表 add constraint ck_成績 check ([成績]>=0 and [成績]<=100)
②在創建表(成績表)的同時,將成績設置檢查約束
create table 成績表(姓名char(20),科目char(20),成績 int check([成績]>=0 and [成績]<=100),學號int foreign key references 學生表(學號))
使用insert插入數據:Insert into 表名 values 〈表中所列的值〉
例如:insert into 成績表 values ('張三','語文','98','1')
成績表中的字段是:姓名 varchar(20), 科目 varchar(20), 成績 int, 學號 int
使用select into 將一個表中的數據添加到另一個表中
(把成績表中的數據添加到成績表1中)insert 目標表的表名 select 從現表中選擇的列 from 原表
create table 成績表1( 姓名 nvarchar (20),科目 nvarchar (20),成績 int )
insert 成績表1 select 姓名,科目,成績 from 成績表
更新表中數據:
更新一行:update 表名 set 列名=values [ where〈查找條件〉]
例如:update 成績表 set 成績=90 where 姓名='張三'
更新多行:update 成績表 set 成績=90
刪除數據:
刪除一行數據:delete from 表名 [where <查找條件>]例如:delete from 成績表 where 姓名='張三'
刪除多行數據:delete from 成績表
使用truncate table 刪除表中的所有數據:truncate table 成績表
查詢數據——語法:select 列名 from 表名
例如:select 姓名,科目,成績 from 成績表 或 select * from 成績表 查詢成績表中所有的數據
1.使用where子句:select * from 表名 where<查找條件>或select 列名 from 表名 where<查找條件>
例如:select * from 成績表 where姓名='張三'或select 成績,科目 from 成績表 where 姓名='張三'
2.使用order by子句(排序)升序(asc)降序(desc)
語法:select * from 表名 order by 列名 或 select 列名 from 表名 order by 列名
例如:select * from 成績表 order by 成績 asc或 select 姓名,成績 from 成績表 order by 成績 desc
3.在查詢中使用常量:select 列名+’:’+列名+’->’+列名(數據類型應一致)
例如:select 姓名+':'+科目 from 成績表 或 select 姓名+':'+科目 as 名單 from 成績表
4.使用as子句命名列:select 列名 as 列名(顯示的名)from 表名
例如:select 成績 as 成績單 from 成績表
5.使用標識列:select identity (datatype標識列的數據類型,標識種子,遞增量)as 列名(將要插入新表中的列的名稱) into table2(現有新表)from table1(要添加標識值的表)(原來的表)
例如:select identity (int,1,1) as 編號 into 成績表1 from 成績表
6.使用top子句限制查詢返回行數
語法:select top n 列名 from 表名(顯示n行)或 select top n percent 列名 from 表名(顯示n%行)
例如:select top 2 成績 from 成績表 或 select top 50 percent 成績 from 成績表
聚合函數:
1.sum(求和):select sum (成績) as 總分 from 成績表
2.avg(求平均):select avg (成績) as 平均分 from 成績表
3.count(計數):select count(成績) as 人數 from 成績表
4.max(最大值):select max (成績) as 最大值 from 成績表
5.min(最小值):select min (成績) as 最小值 from 成績表
使用group by進行分組查詢(與聚合函數配合使用)
select 列名1,聚合函數(列名)as 列名from 表名group by 列名1
例如:select 科目,max (成績) as 最大值 from 成績表 group by 科目
使用having子句選擇行(順序)where→group by→having在分組或使用聚合函數後對行進行篩選
例如:select 科目,max (成績) as 最大值 from 成績表 group by 科目 having max(成績)>65
通配符和模糊查詢:
1.like——select * from 成績表 where 姓名 like '張%'
2.in——select * from 成績表 where 姓名 in('張三')
3.between——select * from 成績表 where 成績 between 80 and 90
4.is null——select * from 成績表 where 姓名 is null
select語句小結:
select [TOP][n]或[n percent] <目標列> [as 別名][,<目標列1> as 別名]…
from<表名或視圖名>[as 別名]…[where 條件表達式…][group by<列名1>[having<條件表達式>]]
[order by<列名2>[ASC升序/DESC降序]]
系統函數:
1.獲取指定字符串中左起第一個字符的ASC碼——print ascii('ABCDEF') --結果爲:65
2.根據給定的ASC碼獲取相應的字符——print char(65) --結果爲:A
3.獲取給定字符串的長度——print len('abcdef') --結果爲:6
4.大小寫轉換——print lower('ABCDEF') --結果爲:abcdef;print upper('abcdef') --結果爲:ABCDEF
5.去空格
左——print ltrim(' abcd dfd df ') --結果爲:'abcd dfd df '
右——print rtrim(' abcd dfd df ') --結果爲:' abcd dfd df'
6.求絕對值——print abs(-12) --結果爲:12
7.冪——print power(3,2) 3 的 2 次方,--結果爲:9。print power(3,3) --結果爲:27
8.隨機數(0—1000之間的隨機數)——print rand() * 1000
9.獲取圓周率——print pi() --結果爲:3.14159
10.獲取系統時間——print getdate() --結果爲:月日年時間,如:06 30 2006 9:40AM
獲取3天前的時間——print dateadd(day, -3 , getdate())
獲取3天后的時間——print dateadd(day, 3 , getdate())
獲取3年前的時間——print dateadd(year, -3 , getdate())
獲取3年後的時間——print dateadd(year, 3 , getdate())
獲取3月後的時間——print dateadd(month, 3 , getdate())
獲取9小時前的時間——print dateadd(hour,-9 , getdate())
獲取9分鐘後的時間——print dateadd(minute, 9 , getdate())
獲取指定時間之間相隔多少年——print datediff(year, '2005-01-01', '2008-01-01')
獲取指定時間之間相隔多少月——print datediff(month, '2005-01-01', '2008-01-01')
獲取指定時間之間相隔多少天——print datediff(day, '2005-01-01', '2008-01-01')
字符串合併——print 'abc' + 'def';print 'abc' + '456'(正確) ;print 'abc' + 456 (錯誤)
類型轉換——print 'abc' + convert(varchar(10), 456) 結果爲:abc456
print convert(varchar(12), '2005-09-01',110) 結果爲:2005-09-01
select title_id, type, price from titles -- 字符串連接必須保證類型一致(以下語句執行將會出錯)
類型轉換——(錯誤)——select title_id + type + price from titles
(正確)——select title_id + type + convert(varchar(10), price) from titles
獲取指定時間的特定部分:
年——print year(getdate());月——print month(getdate());日——print day(getdate())
獲取指定時間的特定部分
年——print datepart(year, getdate()); 月——print datepart(month, getdate())
日——print datepart(day, getdate()); 小時——print datepart(hh, getdate())
分鐘——print datepart(mi, getdate()); 秒——print datepart(ss, getdate())
毫秒——print datepart(ms, getdate())
-- 獲取指定時間的間隔部分——返回跨兩個指定日期的日期和時間邊界數
相差年數——print datediff(year, '2001-01-01', '2008-08-08')
相差月數——print datediff(month, '2001-01-01', '2008-08-08')
相差天數——print datediff(day, '2001-01-01', '2008-08-08')
相差小時數——print datediff(hour, '2001-01-01', '2008-08-08')
相差分鐘數——print datediff(mi, '2001-01-01', '2008-08-08')
相差秒數——print datediff(ss, '2001-01-01', '2008-08-08')
-- 在向指定日期加上一段時間的基礎上,返回新的 datetime 值
加年份——print dateadd(year, 5, getdate())
加月份——print dateadd(month, 5, getdate())
加天數——print dateadd(day, 5, getdate())
加小時——print dateadd(hour, 5, getdate())
加分鐘——print dateadd(mi, 5, getdate())
加秒數——print dateadd(ss, 5, getdate())