1. 程式人生 > >SQL增刪改查,迴圈,觸發器,儲存過程,以及sql語法

SQL增刪改查,迴圈,觸發器,儲存過程,以及sql語法

                                      可以直接貼上程式碼使用

--建立資料庫命令
create database j1216
on
(
name=j1216,
filename='E:\shuju\j1216\j1216.mdf',
size=10,
maxsize=50,
filegrowth=5
)
log on
(
name=j1216_log,
filename='E:\shuju\j1216\j1216_log.ldf',
size=5,
maxsize=25,
filegrowth=5
)
go
-----------------------------------------------------------------------------------
--建立表
--建立學生表
create table tb_student
(
id int identity(1,1) primary key not null,
s_name varchar(20),
sex varchar(10),
age int
)
--建立成績表
create table tb_sc
(
tno varchar(20) primary key not null,
grade int,
sno varchar(20) not null,
c_no int not null
)
--建立課程表
create table tb_course
(
c_id int identity(1,1) primary key not null,
c_no int not null,
c_name varchar(50)
)
--建立部門表
create table tb_depart
(
id int identity(1,1) primary key not null,
d_no int ,
d_name varchar(50)
)
--建立成績表
create table tb_grade
(
g_no varchar(20) primary key not null,
s_no varchar(20) not null,
w_grade int,
l_grade int
)
--建立訂單表
create table OrderDetails
(
OrderD int primary key not null,
ProductD int,
UnitPrice money,
Quantity int
)
--建立貨倉表
create table Products
(
ProductD int primary key not null,
UnetislnStock int
)
---------------------------------------------------------------------------------
--刪除表
select * from  tb_student
select * from  tb_user
select * from OrderDetails;
select * from tb_sc;
drop table tb_sc
drop table tb_student_clone
drop table tb_student_clone2

create table tb_user
(
id int,
uname varchar(20)
)
--------------------------------------------------------------------------------
--使用資料庫
 use j1216
---------------------------------------------------------------------------------
--修改表的欄位型別
alter table tb_student alter column s_name varchar(30)
--刪除欄位
alter table tb_student drop column age
--新增欄位
alter table tb_student add  age int
alter table tb_student add tno varchar(20)
alter table tb_student add d_no int
--欄位重新命名
exec sp_rename 'tb_student.s_name','sname','column'
--------------------------------------------------------------------------------
-------給表新增主鍵
----新增列語法:ALTER TABLE 表名 Add 列名 型別 ...
alter table tb_user add userid int not null identity(10,1);

------ 語法:   alter table 表名 add constraint 約束名 primary key (你的主鍵);  
alter table tb_user add constraint pk_tb_user primary key (userid);

--給表tb_student新增外來鍵
----- 語法:alter table 表名 add constraint 約束名 foreign key (你的外來鍵) references (表名)(欄位名)
------ 指定表中的資料是否用新新增的或重新啟用的 FOREIGN KEY 或 CHECK 約束進行驗證。如果沒有指定,對於新約束,假定為 WITH CHECK,對於重新啟用的約束,假定為 WITH NOCHECK
alter table tb_student with check add constraint pk_tno
foreign key(tno) references tb_sc(tno)

--給表OrderDetails新增外來鍵
alter table OrderDetails with nocheck add constraint pk_ProductD
foreign key(ProductD) references Products(ProductD)
---------------------------------------------------------------------------------
--向表中新增資料
--向學生表中新增資料
insert into  tb_student(s_name,sex,age,tno,d_no) values('張三','男',21,'1203',15);
insert into  tb_student(s_name,sex,age,tno,d_no) values('歐陽鋒','男',120,'1208',63);
insert into  tb_student(s_name,sex,age,tno,d_no) values('歐陽亞雄','男',27,'1203',42);
insert into  tb_student(s_name,sex,age,tno,d_no) values('DB_i11','男',32,'1207',77);
insert into  tb_student(s_name,sex,age,tno,d_no) values('DB_ii1111','男',23,'1201',56);
--向成績表中新增資料
insert into tb_sc(tno,grade,sno,c_no) values('1201',85,'1',1000)
insert into tb_sc(tno,grade,sno,c_no) values('1202',80,'2',1001)
insert into tb_sc(tno,grade,sno,c_no) values('1203',77,'1',1000)
insert into tb_sc(tno,grade,sno,c_no) values('1204',65,'2',1001)
insert into tb_sc(tno,grade,sno,c_no) values('1205',45,'1',1000)
insert into tb_sc(tno,grade,sno,c_no) values('1206',98,'1',1000)
insert into tb_sc(tno,grade,sno,c_no) values('1207',78,'2',1001)
insert into tb_sc(tno,grade,sno,c_no) values('1208',86,'2',1001)
--向課程表中新增資料
insert into tb_course(c_no,c_name) values(1000,'java')
insert into tb_course(c_no,c_name) values(1001,'c++')
insert into tb_course(c_no,c_name) values(1002,'c#')
insert into tb_course(c_no,c_name) values(1003,'.net')
insert into tb_course(c_no,c_name) values(1004,'php')
insert into tb_course(c_no,c_name) values(1005,'android')
--向院系表中新增資訊
insert into tb_depart(d_no,d_name) values(1111,'計算機學院')
insert into tb_depart(d_no,d_name) values(2222,'管理學院')
insert into tb_depart(d_no,d_name) values(3333,'旅遊學院')
insert into tb_depart(d_no,d_name) values(4444,'烹飪學院')
--向貨倉表中新增資料
insert into Products(ProductD,UnetislnStock) values(1,15)
insert into Products(ProductD,UnetislnStock) values(2,65)
insert into Products(ProductD,UnetislnStock) values(3,20)
insert into Products(ProductD,UnetislnStock) values(4,50)
--向訂單表中新增資料
insert into OrderDetails(OrderD, ProductD, UnitPrice, Quantity) values(10522,1,31.00,6)
insert into OrderDetails(OrderD, ProductD, UnitPrice, Quantity) values(10523,2,9.65,7)
insert into OrderDetails(OrderD, ProductD, UnitPrice, Quantity) values(10524,3,30.00,10)
insert into OrderDetails(OrderD, ProductD, UnitPrice, Quantity) values(10525,4,19.00,5)
-----------------------------------------------------------------------------
--迴圈向tb_grade表中新增資料
--宣告變數
declare @t int
declare @a int
declare @s int
   --隨即產生1-100之間的整數
   set @t=rand()*100
   set @a=rand()*100
   print @t;
   print @a;
   set @s=0
   print @s;
while(@s<100)
begin
   if(@t>10 and @a>10)
       begin
             -----一般來講cast()適用範圍略廣,convert(),一般用於日期和字串之間進行轉換SELECT CAST(CONVERT(CHAR(10),CURRENT_TIMESTAMP,121) AS DATETIME
          insert into tb_grade(g_no, s_no, w_grade, l_grade) values('s27181'+cast(@s as varchar(2)),'s2530'+cast(@s as varchar(2)),@t,@a)
          set @t=rand()*100
          set @a=rand()*100
       end
          set @
[email protected]
+1 end go select * from tb_grade; select * from tb_student; --------------------------------------------------------------------------------- --修改表中資訊 update tb_student set sex='女' where s_name like '%三' update tb_student set sex='男' where s_name like 'DB%' update tb_student set d_no=1111 where id<7 update tb_student set d_no=2222 where id<23 and id>=21 --------------------------------------------------------------------------------- --刪除整張表的資訊 delete from tb_student delete from tb_student_clone delete from tb_student_clone2 delete from tb_sc delete from tb_grade delete from OrderDetails delete from Products --刪除部分資料 delete from tb_student where id=1 delete from tb_student where s_name like '歐陽%' --------------------------------------------------------------------------------- --查詢語句 select * from tb_student select * from tb_sc select * from tb_course select * from tb_grade select * from tb_student_clone select * from tb_student_clone2 select * from Products select * from OrderDetails --根據id降序查詢 select * from tb_student order by id desc --根據id升序查詢 select * from tb_student order by id asc --查詢所有年齡在20歲以下的學生的姓名及其年齡 select s_name,age from tb_student where age>20 --查詢年齡在20到25歲之間的學生的資訊 select * from tb_student where age>20 and age<25 select * from tb_student where age between 21 and 24 --查詢姓"歐陽"且全名只有3個字的學生的姓名 --- sql中like用法 : --- * 它同於DOS命令中的萬用字元,代表多個字元。 (如:c*c代表cc,cBc,cbc,cabdfec等) --- % 這種方法在很多程式中要用到,主要是查詢包含子串的。 (如:%c%代表agdcagd等) --- [*] 代替* (如:a[*]a代表a*a) --- ? 同於DOS命令中的?萬用字元,代表單個字元 (如:b?b代表brb,bFb等) --- # 大致同上,不同的是代只能代表單個數字。 (如:k#k代表k1k,k8k,k0k) --- _ 指定一個範圍中任意一個 (如:[a-z]代表a到z的26個字母中任意一個) --- [!字元] 它只代表單個字元 (如:[!a-z]代表9,0,%,*等) --- [!數字] 它只代表單個字元 (如:[!0-9]代表A,b,C,d等) --- 字元[範圍型別]字元 可以和其它幾種方式組合使用 (如:cc[!a-d]#代表ccF#等) select s_name from tb_student where s_name like '歐陽_' select s_name from tb_student where s_name like '歐陽%' and len(s_name)=3 --查詢"DB_"開頭,且倒數第三個字元為i的課程的詳細情況 --當記錄中有萬用字元時使用轉義\escape '\' select * from tb_student where s_name like 'DB\_%i__'escape '\' --查詢選修了3號課程的學生的學號及其成績,查詢結果按分數的降序排列 select sno,grade from tb_sc where sno=3 order by grade desc --查詢男女生各有多少人 select count(*)from tb_student where sex='男' union select count(*)from tb_student where sex='女' --按性別分組查詢 select sex as '性別',count(*) as '人數' from tb_student group by sex ---------------------------------------------------------------------------------- --把相同的欄位去掉 select distinct sex from tb_student --truncate 和delete,truncate 執行的速度比delete快 --刪除全部資料,保留表的結構 truncate table tb_course ---------------------------------------------------------------------------------- --T-SQL --迴圈想表中新增資料的SQL指令碼 declare @t int --宣告一個整型變數 declare @s char(2) --性別 set @t=0 --給整型變數賦值 while(@t<10) --迴圈 begin --迴圈體 if(@t%2!=0) set @s='男' else set @s='女' insert into tb_student(s_name,sex,age,tno) values('劉備'+cast(@t as varchar(2)),@s,
[email protected]
,cast(([email protected]) as varchar(30) )) set @[email protected]+1 end --迴圈修改表中的資料 declare @t int --宣告一個變數 declare @s int set @t=1197 --給整型變數賦值 set @s=31 while(@t<1204) --迴圈 begin --迴圈體 update tb_student set [email protected] where [email protected]
set @[email protected]+1 set @[email protected]+1 end ---------------------------------------------------------------------------------- --複製表 select * into tb_student_clone from tb_student where 1=1 --複製表結構 select * into tb_student_clone2 from tb_student where 1=2 ----------------------------------------------------------------------------------- --分頁每頁顯示5條記錄 select top 5 * from tb_student select top 5 * from tb_student order by id asc --顯示第二頁 select top 5 * from tb_student where id not in(select top 5 id from tb_student) ----------------------------------------------------------------------------------- --冒牌分頁 declare @t1 int --宣告一個整型變數 declare @pagecount int set @t1=0 --給整型變數賦值 set @pagecount=(cast((select count(*) as count from tb_student) as int)/5)+1; print @pagecount; while(@t1<(@pagecount)) --迴圈 begin --迴圈體 select top 5 * from tb_student where id not in(select top (5*@t1) id from tb_student) set @[email protected]+1 end ------------------------------------------------------------------------------------- --每頁顯示m條資料,查詢第n頁結果 declare @m int ---每頁顯示多少條資料 declare @n int --- set @m=5 set @n=(cast((select count(*) as count from tb_student) as int)/5)+1; print @n if (@n-1)>0 begin select top (@m) * from tb_student where id not in(select top (@m*(@n-1)) id from tb_student) end ------------------------------------------------------------------------------------ --求交集,可以直接用and select * from tb_student where sex='女' intersect select * from tb_student where age>35 --求並集 系統會自動將重複的元組去掉 select * from tb_student where sex='男' union select * from tb_student where age>21 ----求交集 系統保留重複元素組 select * from tb_student where sex='男' union all select * from tb_student where age>21 --求補集 select * from tb_student where sex='男' except select * from tb_student where age<30 ------------------------------------------------------------------------------------ --獲得當前增量的值 identity--系統變數 select @@identity as abc ----------------------------------------------------------------------------------- --cast型別轉換函式 select cast('123' as int) select cast('2012-12-11' as datetime) select cast(CONVERT(varchar(800),GETDATE(),121) as datetime) --convert型別轉換函式 select convert(datetime, '2012-12-11') --獲取當前時間 select current_timestamp --獲取當前主機埠號和主機名 select host_id() as '主機埠號',host_name() as '主機名' ----------------------------------------------------------------------------------- --字串的連線 select * from tb_student where s_name=('劉備'+'0') --當表中不存在此欄位時,系統會自動建立一個虛列欄位 select *,('abc'+'123') as a from tb_student select * from tb_student select * from tb_depart ----------------------------------------------------------------------------------- --多表查詢 select distinct * from tb_student as s,tb_course as c,tb_sc as sc where s.tno=sc.tno and c.c_no=sc.c_no --連線查詢 --內聯查詢 select a.*,b.d_name from tb_student a inner join tb_depart b on b.d_name='計算機學院' and a.d_no=b.d_no --左連查詢,以左邊表為基表,滿足條件的查詢出來,不滿足條件用null填充 select * from tb_student a left join tb_depart b on a.d_no=b.d_no and b.d_name='計算機學院' --右連查詢,以右邊表為基表,滿足條件的查詢出來,不滿足條件用null填充 select * from tb_student a right join tb_depart b on a.d_no=b.d_no and b.d_name='計算機學院' --巢狀查詢 select * from tb_depart as a where a.d_no in(select d_no from tb_student where s_name='張三') select * from tb_depart as a where a.d_no not in(select d_no from tb_student where s_name='張三') --------------------------------------------------------------------------------- --建立檢視 create view view_sc as select a.*,b.d_name from tb_student a right join tb_depart b on a.d_no=b.d_no and b.d_name='計算機學院' --查詢檢視 select * from view_sc a,tb_sc b where a.tno=b.tno --------------------------------------------------------------------------------- --判斷資料庫是否存在,如果存在,就刪除它 if exists (select * from sysdatabases where name='j1216') drop database j1216 --判斷表在資料庫中是否存在,如果存在,就刪除它 if exists (select * from sysdatabases where name='tb_sc') drop table tb_sc -------------------------------------------------------------------------------- --定義變數儲存表中的記錄 declare @t2 int select @t2=count(*) from tb_student print @t2; --列印變數 ----print 直接返回一個值 ----select 返回一個帶有結構的值,比如說有列名 print @t2 select @t2 -------------------------------------------------------------------------------- --全域性變數的使用 --列印SQL Server的版本 print 'SQL Server的版本: '[email protected]@VERSION --列印伺服器的名稱 print '伺服器的名稱: '[email protected]@SERVERNAME --向tb_student表中新增一行資料 INSERT INTO tb_student(s_name,sex,age,tno,d_no) VALUES('武松','男',23,'1205',63) --如果大於0表示上一條語句執行有錯誤 print '當前錯誤號: '+convert(varchar(5),@@ERROR) --列印剛在表中新增的資料的ID號 print '剛才報名的學員,座位號為:' +convert(varchar(5),@@IDENTITY ) --修改tb_student表中姓名為'李四'的學生的年齡 UPDATE tb_student SET age=85 WHERE s_name='李四' --如果大於0表示上一條語句執行有錯誤 print '當前錯誤號: '+convert(varchar(5),@@ERROR) --GO是批處理的標誌, --表示SQL Server將這些T-SQL語句編譯為一個執行單元,提高執行效率 GO -------------------------------------------------------------------------------- --if-else語句的使用 declare @a float select @a=avg(w_grade) from tb_grade print @a print '平均分是:'+convert(varchar(10),@a) if(@a>=60) begin print '平均成績:良' select top 3 g_no, s_no, w_grade from tb_grade order by w_grade desc end else begin print '平均成績:差' select top 3 g_no, s_no, w_grade from tb_grade order by w_grade asc end go --------------------------------------------------------------------------------- --while迴圈語句 declare @a1 float while(1=1) begin select @a1=count(*) from tb_grade where w_grade<60 print @a1 if(@a1>0) begin update tb_grade set w_grade=w_grade+2 where w_grade<60 end else begin break; end end go select * from tb_grade; --變數儲存小於60分的學生人數 declare @c int select @c=count(*) from tb_grade where w_grade<60 while(@c>0) begin update tb_grade set w_grade=w_grade+2 select @c=count(*) from tb_grade where w_grade<60 end go ------------------------------------------------------------------------------- --case end ---相當於switch select *, case when w_grade>=90 then 'A' when w_grade>=80 and w_grade<=89 then 'B' when w_grade>=70 and w_grade<=79 then 'C' when w_grade>=60 and w_grade<=69 then 'D' else 'E' end as '成績評定' from tb_grade go ------------------------------------------------------------------------------- --觸發器的語法 ---- create trigger triggerName on tableName ---- for delete,|insert,|update ---- as ---- begin ---- --T-SQL ---- end --建立一張備份表 select * into tb_student_clone from tb_student where 1=2 --建立觸發器的指令碼 --deleted inserted是刪除,增加時呼叫的虛擬表 drop trigger tg_student; drop trigger tg_student1; drop trigger tg_student2; ------ tb_student和tb_sc有主外來鍵關聯,建立刪除觸發器需要先刪除從表後刪主表 ---------------------------------刪除觸發器 create trigger tg_student on tb_student for delete as begin insert into tb_student_clone(id,s_name,sex,age,tno,d_no) select id,s_name,sex,age,tno,d_no from deleted end ----呼叫觸發器 delete from tb_student where id=25 ---報錯: 當 IDENTITY_INSERT 設定為 OFF 時,不能為表 'tb_student_clone' 中的標識列插入顯式值。 --------正確如下: create trigger tg_student1 on tb_student for delete as begin set IDENTITY_INSERT tb_student_clone on insert into tb_student_clone(id,s_name,sex,age,tno,d_no) select id,s_name,sex,age,tno,d_no from deleted end -------------------------插入觸發器 create trigger tg_student2 on tb_student for insert as begin set IDENTITY_INSERT tb_student_clone on insert into tb_student_clone(id,s_name,sex,age,tno,d_no) select id,s_name,sex,age,tno,d_no from inserted end --觸發器的呼叫 insert into tb_student(s_name,sex,age,tno,d_no) values('','',25,'1206',9) select * from tb_student_clone --刪除觸發器 drop trigger tg_student --禁用觸發器 disable trigger tg_student on tb_student disable trigger tg_student2 on tb_student --啟用觸發器 enable trigger tg_student on tb_student --修改觸發器 只需要在建立觸發器的指令碼中將create改為alter alter trigger tg_student on tb_student for delete,update as begin set IDENTITY_INSERT tb_student_clone on insert into tb_student_clone(id,s_name,sex,age,tno,d_no) select id,s_name,sex,age,tno,d_no from deleted end --------------------------------------------------------------------------------------- --建立觸發器,使得在向OrderDetails表中新增資料時,貨倉表中的貨物數量UnetislnStock --則要減去相應的訂單表中預定的數量Quantity create trigger tg_order on OrderDetails for insert as begin [email protected]是訂單中產品數量 declare @a int [email protected]是訂單中產品號碼 declare @b int select @a=Quantity from inserted select @b=ProductD from inserted update Products set UnetislnStock=([email protected]) where [email protected] end --禁用觸發器 disable trigger tri_order on OrderDetails --啟用觸發器 enable trigger tri_order on OrderDetails --呼叫觸發器 insert into OrderDetails(OrderD, ProductD, UnitPrice, Quantity) values(10527,4,19.00,10) select * from Products select * from OrderDetails; ------------------------------------------------------------------------------------------- --建立無參儲存過程 create proc pro_2 as begin insert into tb_student( s_name, sex, age, tno, d_no) values('李剛','男',35,'1207',8) end --呼叫儲存過程 exec pro_2 --建立帶引數的儲存過程,輸入和輸出引數(用output定義的引數為輸出引數) --用in定義的引數是輸入引數(in可以不寫) create proc pro_4(@name varchar(20),@sex varchar(2), @age int,@tno varchar(50),@d_no int,@c int output) as begin insert into tb_student(s_name, sex, age, tno, d_no) values(@name,@sex,@age,@tno,@d_no) set @[email protected]@rowcount print '新增'+convert(varchar(5),@c)+'條資料' end --呼叫儲存過程 declare @a int exec pro_4 '鳳姐','女',30,'1203',250,@a --修改儲存過程 只需要在建立儲存過程的指令碼中將create改為alter alter proc pro_4(@name varchar(20),@sex varchar(2), @age int,@tno varchar(50),@d_no int,@c int output) as begin if @name='' begin raiserror('姓名不能為空',17,1) return end insert into tb_student(s_name, sex, age, tno, d_no) values(@name,@sex,@age,@tno,@d_no) set @[email protected]@rowcount print '新增'+convert(varchar(5),@c)+'條資料' end --呼叫儲存過程 declare @a int exec pro_4 '','女',30,'1207',250,@a declare @a int exec pro_4 '伏羲','女',30,'1207',250,@a --刪除儲存過程 drop proc pro_2 ---------------------------------------------------------------------------------------- --儲存過程:查詢資料庫中指定開始行到結束行記錄 create proc pro_zuoye(@a int,@b int) as begin select * from tb_student where id not in(select top (@a-1) id from tb_student) intersect select * from tb_student where id in(select top (@b) id from tb_student ) end --呼叫儲存過程 exec pro_zuoye 5,8 --------------------簡單的分頁,使用儲存過程 USE [j1216] GO /****** Object: StoredProcedure [dbo].[Sp_PapeView] Script Date: 07/24/2013 15:45:31 ******/ SET ANSI_NULLS OFF GO SET QUOTED_IDENTIFIER ON GO create proc Sp_PageView ( @RecordCount int OUTPUT, --總記錄數 @PageSize int=4, --每頁的大小(記錄數) @PageCurrent int=1, --要顯示的頁碼 @PageCount int OUTPUT --總頁數 ) as begin select @RecordCount=COUNT(*) from tb_student select @[email protected]/@PageSize+1 select top (@PageSize) * from tb_student where id not in (select top ((@PageCurrent-1)*@PageCount) id from tb_student) end declare @RecordCount int,@PageCount int exec sp_pageView @RecordCount,5,1,@PageCount ----------------------------------------------------------------------------------------- --備註:凡是使用create函式建立的資料庫元素,全部都用drop來刪除