1、數據庫設計
數據庫設計的重要性:
減少冗余,提高性能、易維護
數據庫設計的步驟:
1、收集信息、標識對象、標識屬性、標識關系(一對一、一對多、多對一、多對多)
E-R圖:
屬性:定義實體的性質、實體的特征
實體:數據項(屬性)的集合
關聯:實體之間相互連接的方式

簡單理解一下就可以了

數據庫規范化:
第一范式(1NF):
每列都應該是原子性的,五重復的域
第二范式(2NF):
在第一范式的基礎上屬性完全依賴於主鍵
第三范式(3NF):
第三范式要求各列與主鍵列直接相關
T-SQL語句創建和管理數據庫和表:
T-SQL創建數據庫:
if DB_ID('數據庫名') is not null drop database 數據庫名 go create database 數據庫名 on ( name='數據庫名', filename='物理數據庫儲存路徑數據庫文件' )
案例:
if DB_ID('Student')is not null drop databese Student go create databese Student on ( name='Student', finema='E:\第二學期\SQL\stuDB\Student.mdf' )
| 數據文件參數 | 描述 |
| name | 數據庫邏輯名稱 |
| filename | 數據庫物理文件名 |
| size | 數據文件初始化大小,單位默認為M |
| maxsize | 數據文件可增長到最大值,單位默認阿M,不指定即無限大 |
| filegrowth | 數據庫每次增長率,可以是百分比,默認單位M,0不增長 |
T-SQL語句創建表:
if object_ID('表名')is not null drop table 表名 go create table 表名 ( 字段1 數據類型 列的特性, 字段2 數據類型 列的特性 )
案例:
if object_ID('StuInfo')is not null drop table StuInfo go create table StuInfo ( StuId int identity(1,1) primary key, StuName varchar(10) not null, StuSex varchar(2) not null, StuAge varchar(3) not null )
T-SQL創建約束:
主鍵約束:(primary key constraint):主鍵列數據唯一,並不為空,簡稱:PK
唯一約束:(unique constraint):保證該列不允許除夕重復值,簡稱:UQ
檢查約束:(check constraint):限制列中允許的取值以及多個列直接的關系,簡稱:CK
默認約束:(default constraint):設置某列的默認值,簡稱:DF
外鍵約束:(foreign key constraint):用於在兩個表之間建立關系,需要指定主從表,簡稱:FK
T-SQL添加約束的語法格式:
alter table 表名
add constraint 約束名 約束類型 具體的約束說明
T-SQL刪除約束:
alter table 表名
drop constraint 約束名
案例:
--添加主鍵約束(將StuNo設為主鍵) alter table StuInfo add constraint PK_StuNO primary key (StuNo) go --添加默認約束(性別默認為男) alter table StuInfo Add constraint DF_StuSex DEFAULT ('男')for StuSex go --添加檢查約束(年齡必須為40之間) alter table StuInfo Add constraint CK_StuAge check(StuAge>=18 and StuAge<=40) go --添加外鍵約束 alter table Exam Add constraint FK_StuNo FORELGN KEY (StuNo)references StuInfo(StuNo) go
(1)對表結構的操作
1、在表中添加一列
語法:alter table 表名
add 添加的列名 數據類型
例子:在Student表中添加列Hobbies,類型為varchar,寬度:20
alter table Student
add Hobbies varchar(20)
2、刪除表中的一列
語法:alter table 表名
drop column 列名
例子:刪除Student表中的Hobbies列
alter table Student
drop column Hobbies
3、修改表中列的數據類型
語法:alter table 表名
alter column 列名 修改后的數據類型 not null
例子:修改Student中的Sex列為char型,寬度為2
alter table Student
alter column Sex char(2) nou null
(2)添加約束
語法:alter table 表名
add constraint 約束名 primary key(要設置主鍵的列名)
例子:
給Class表添加主鍵約束
if OBJECT_ID('PK_ClassId') is not null
alter table Class
drop constraint PK_ClassId
go
alter table Class
add constraint PK_ClassId primary key(ClassId)
2、添加唯一約束
語法:alter table 表名
add constraint 約束名 unique(要添加唯一約束的列名)
例子:
給信息表stuInfo中的姓名添加唯一約束
if OBJECT_ID('UQ_StuName') is not null
alter table StuInfo
drop constraint UQ_StuName
go
alter table StuInfo
add constraint UQ_StuName
unique(StuName)
3、添加默認約束
語法:alter table 表名
add constraint 約束名 Default(默認值) for 要添加默認值的列名
例子:
給stuInfo表中的Age列添加默認值為18
if OBJECT_ID('DF_Age') is not null
alter table StuInfo
drop constraint DF_Age
go
alter table stuInfo
add constraint DF_Age Default(18) for Age
4、添加檢查約束
語法:alter table 表名
drop constraint 約束名
check(列名>=0)
例子:
給筆試成績添加一個約束,要求成績必須在0-100之間
if OBJECT_ID('CK_WriteExam') is not null
alter table Exam
drop constraint CK_WriteExam
go
alter table Exam
add constraint CK_WriteExam
check(WriteExam>=0 and WriteExam<=100)
5、外鍵約束
語法:alter table 表名1
add constraint 約束名
foreign key(外鍵約束名)
references 表名2(外鍵約束名)
例子:
給班級表與學員信息表創建關系(外鍵約束)
if OBJECT_ID('FK_Class_StuInfo') is not null
alter table stuInfo
drop constraint Fk_Class_StuInfo
go
alter table stuInfo
add constraint Fk_Class_StuInfo
foreign key(ClassId)
references Class(ClassId)
--刪除約束
Alter table 表名
Drop ConStraint 約束名
--刪除表
Drop table 表名
(3)高級查詢語法格式
--內連接
語法:
select 要查詢的屬性
from 表1 inner join 表2
on 表1.Id=表2.Id
where 要限制的條件(可以不要)
--左外連接
語法:
select 要查詢的屬性
from 表1 left outer join 表2
on 表1.id=表2.id
--右外連接
語法:
select 要查詢的屬性
from 表1 right outer join 表2
on 表1.id=表2.id
--全外連接
語法:
select 要查詢的屬性
from 表1 full outer join 表2
on 表1.id=表2.id
--交叉連接
語法:
select 要查詢的屬性
from 表1 Cross join 表2
where 條件
--自連接
select 要查詢的屬性
from 表1 , 表2
where 表1.id=表2.id
(4)高級查詢實例
if DB_ID('GoodSystem') is not null
drop database GoodSystem
go
create database GoodSystem on --創建一個商品數據庫
(
name='GoodSystem',
filename='E:\SQL\第二章上機任務\GoodSystem.mdf'
)
--打開數據庫
use GoodSystem
--創建商品類型表GoodsType
if OBJECT_ID('GoodType') is not null
drop table GoodType
go
create table GoodType
(
Tid int primary key,
Type varchar(20)
)
--創建商品信息表Goods
if OBJECT_ID('Goods') is not null
drop table Goods
go
create table Goods
(
id int primary key,
Tid int ,
Name varchar(50),
Price money,
ProductionDate datetime,
Amount int
)
--給商品類型表GoodsType添加測試數據
insert GoodType select '1','家電' union
select '2','電子' union
select '3','食品' union
select '4','生活用品'
--給商品信息表Goods添加測試數據
insert Goods select '1','1','冰箱','3344','2017-6-3','100' union
select '2','1','電視','1777','2016-10-4','100' union
select '3','1','微波爐','333','2017-2-26','100' union
select '4','2','手機','4500','2017-5-7','100' union
select '5','2','顯示器','1777','2016-12-4','100' union
select '6','2','主機','1500','2017-3-9','100' union
select '7','3','老干媽','9','2017-7-6','100' union
select '8','3','爽口榨菜','3.6','2017-6-8','100'
--查詢商信息表中的商品名稱,價錢,生產日期。
select Name 商品名稱,Price 價錢,ProductionDate 生產日期
from Goods
--查詢商品類型、商品名稱、價錢、生產日期
select gt.Type 商品類型,gs.Name 商品名稱 , gs.Price 商品價錢,gs.ProductionDate 生產日期
from GoodType gt inner join Goods gs
on gt.Tid=gs.Tid
--查詢生產日期為2017的商品類型、商品名稱、價錢、生產日期
select gt.Type 商品類型,gs.Name 商品名稱 , gs.Price 價錢,gs.ProductionDate 生產日期
from GoodType gt inner join Goods gs
on gt.Tid=gs.Tid and year(gs.ProductionDate) like '2017%'
--查詢商品類型為“電子”的商品類型、商品名稱、價錢、生產日期,數據按價錢降序排列
select gt.Type 商品類型,gs.Name 商品名稱,gs.Price 價錢 ,gs.ProductionDate 生產日期
from GoodType gt inner join GoodS gs
on gt.Tid=gs.Tid and gt.Type='電子'
order by Price desc
--統計每種商品類型的商品數量
select gt.Type 商品類型, COUNT(gs.Amount) 商品數量
from GoodType gt inner join Goods gs
on gt.Tid=gs.Tid
group by gt.Type
--查詢所有商品類型對應的所有商品信息
select gt.Type 商品類型,gs.Name 商品名稱 , gs.Price 商品價錢,gs.ProductionDate 生產日期
from GoodType gt left join Goods gs
on gt.Tid=gs.Tid
--查詢價錢是333、1500、4500的商品信息
select Type 商品類型,Name 商品名稱,Price 商品價錢,ProductionDate 生產日期
from GoodType gt ,Goods gs
where Price in(333,1500,4500)
and (gs.Tid=gt.Tid)
--查詢沒有對應商品信息的商品類型信息(類型編號,類型名稱)
select Tid 編號,Type 類型 from GoodType
where Tid not in
(select Tid from Goods)
--查詢所有商品的平均價錢
select AVG(Price) 平均價錢 from Goods
--查詢價錢大於平均價錢的商品信息
select Type 商品類型,Name 商品名稱,Price 商品價錢,ProductionDate 生產日期
from GoodType gt , Goods gs
where gs.Tid=gt.Tid
and Price>
(select AVG(Price) 平均價錢 from Goods)
--查詢每種商品類型平均價錢超出總平均價錢的類型名稱、平均價錢
select gt.Type 類型名稱,AVG(Price) 價錢
from Goods gs,GoodType gt
where gs.Tid=gt.Tid
and
gs.Tid in
(select gs.Tid
from Goods
group by Tid
having AVG(Price)>
(select AVG(Price) 平均價錢 from Goods))
group by gt.Type
--查詢所有商品總金額超20萬的商品類型、名稱、總金額
select Type 商品類型 ,Name 名稱 ,Price*Amount 總金額
from GoodS gs , GoodType gt
where gs.Tid=gt.Tid
and Price*Amount>200000
--庫存報警(低10)
--延遲到14:03:00 執行查詢
waitfor time '14:03:00'
select*from Goods
--延遲兩秒執行操作
waitfor delay '00:00:02'
select *from Goods
(5)變量函數
--常用的數學函數
--1、ABS 求絕對值 交易之前-交易之后
--2、POWER 求次方
select POWER(2,10),POWER(2.0000,0.5) --1kb 1024
select POWER(2.0000000,1.000000/3)
--3、求圓周率
select PI()
--4、Rount() --四舍五入函數
select ROUND(315.4567,2),Round(315.4567,0),Round(345.4567,-2)
--5、ceiling --取比原數大的整數
--6、floor --取比原數小的整數
select CEILING(3.00000000001),FLOOR(3.99999999)
--7、ASCII 返回一個字符的ASCII碼值
select ASCII('A')
--8、Rand() 返回一個0-1之間的隨機數
--select nCHAR(214)+nCHAR(208)
select RAND()
select RAND(DATEPART(ss,GetDate())*2)--這樣打變化頻率小
go
--產生一個銀行卡號,前8位為'6225 3800' 后8位為隨機數字,
--請用T-SQL編碼完成
--select RAND()
declare @rand numeric(20,8)
select @rand=RAND()
print @rand
declare @s varchar(16)
set @s=SUBSTRING(STR(@rand,10,8),3,8)
print @s
set @s='62253800'+@s
print '你的新銀行卡號為:'+@s
--日期函數
--1、getdate():返回服務器上的當前時間
select GETDATE()
--2、datepart:返回一個日期的一部分值(整形)
--3、datename:返回一個日期的一部分值(字符串)
--返回一周的第幾天(星期天是第一天)
select DATEPART(DW,GETDATE()),DATENAME(DW,GETDATE())
--返回一年的第幾周
select DATEPART(WEEK,GETDATE()),DATENAME(WEEK,GETDATE())
--4、datediff 日期比較函數
--返回每個交易已經發生了多少天
select DATEDIFF(DD,transdate,GETDATE()) from TransInfo
--字符串函數
--1、LEN:返回一個字符串的字符數
select LEN('中國'),LEN('abc123!')
select LEN('abc '),LEN(' abc')--數據類型為varchar類型,會自動消除沒字符連接的空格
--2、dataLength:返回一個字符串的字節數
select dataLength('中國'),dataLength('abc123!')
select RIGHT('abcdef',3),LEFT('abcdef',3)
--4、substring:字符串截取函數
select SUBSTRING('abcdef',2,3)--和C#不一樣,下標從一開始
--5、charIndex:字符串查找函數
select charIndex('a','bcad',1)
--6、upper:字母大寫轉換函數
--7、lower:字母小寫轉換函數
select UPPER('abc123'),LOWER('abCCC123中!')
--8、space:產生空格函數
select len('abc'+SPACE(10) +'123') ,'abc'+SPACE(10) +'123' --len是測定總長度
--9、replicate:字符串重復函數
select REPLICATE('abc',3)
--10、replace:字符替換函數
select REPLACE('11111111','1','o')--將1替換為o
select REPLACE('o0o0o0o0000oo','0','o'),'00000000'--將0替換為o
select REPLACE( REPLACE('0o0oil0oillil10ol1','l','1'),'0','o')
--11、stuff:字符替換函數
select STUFF('湖南武漢',2,1,'北')
select STUFF('中國長沙',3,0,'湖南')--輸出中國湖南長沙
--12、ltrim和rtrim:去掉字符串左邊或右邊的全部空格
select len(ltrim(' a bc'))
--13、str:將數值轉換為字符串函數
select STR(12345.65,8,2)
--14、char:將一個ASCII碼值轉換為一個字符
select CHAR(97),ASCII('a')
(6)數據庫變量格式
use StuDB
select*from StuInfo
select*from Exam
--總學生人數 參考人數 及格人數 未及格人數 及格率
declare @total int,@sum int,@pass int
select @total=COUNT(*) from StuInfo --統計總人數
select @sum=COUNT(*) from Exam --統計參考人數
select @pass=COUNT(*) from Exam
where WriteExam>=60 and LadExam>=60 --統計及格人數
select @total 總人數,@sum 參考人數,@pass 及格人數 ,
@total-@pass 未及格人數,CONVERT(varchar(20),
ceiling( @pass*1.0/@total*10000)/100)+'%' 及格率
select*from StuInfo
--查看上一個錯誤的編號
select @@ERROR
select*from StuInfo
select*from Class
select @@IDENTITY
insert Class values('s149')
--獲取上一次SQL指令影響的命令行數
select @@ROWCOUNT
--判斷刪除是否成功
--1、直接刪除
--2、先查詢,然后再刪除,再查詢
--當前SQL服務器名稱,當前服務名稱
select @@SERVERNAME ,@@SERVICENAME
--顯示當前打開的事務數
select @@TRANCOUNT
--顯示當前服務器允許的最大連接數
select @@MAX_CONNECTIONS
--顯示當前使用的語言
select @@LANGUAGE
print '當前服務器名稱:' +@@servername
print '當前服務名稱:' +@@servicename
print '錯誤編號:' +convert(varchar(6), @@error)
--顯示筆試平均成績,再根據平均成績顯示相應信息
declare @avg float
select @avg=AVG(writeExam) from Exam
print ' ------成績信息如下:--------'
print'全校平均成績:'+convert(varchar(20),@avg)
if @avg>=70
begin
print'成績優秀!'
--顯示前三名的學員信息
select top 3 StuName,si.StuId,WriteExam,LadExam
from StuInfo si,Exam e
where si.StuId=e.StuId
order by WriteExam desc --筆試降序
end
else
begin
print'成績比較差!'
--顯示后三名的學員信息
select top 3 StuName,si.StuId,WriteExam,LadExam
from StuInfo si,Exam e
where si.StuId=e.StuId
order by WriteExam asc --筆試降序
end
--對全班學員進行提分,保證每位同學的筆試成績全部通過
while(1=1) --永真循環
begin
declare @count int --保存未通過的人數
--統計為通過的人數
select @count=Count(*) from Exam where writeExam<60
if (@count=0)
begin
break --終止循環
end
--進行加分
update Exam set WriteExam=100 where writeExam>=98
update Exam set WriteExam=WriteExam+2 where WriteExam<98
end
print'----------加分后的學員成績如下:--------------'
select*from Exam
--顯示學員筆試成績的等級制
--90以上:優秀,80-90:良好,70-80:中等,60-69 :一般
--60以下:不及格
select ExamNo 考號,StuId 學號,WriteExam 筆試成績 ,LadExam 機試成績,
等級=
case
when writeExam>=90 then '優秀'
when writeExam>=80 then '良好'
when writeExam>=70 then '中等'
when writeExam>=60 then '一般'
else '不及格'
end
from Exam
--顯示所有學員打的姓名,性別,年齡,筆試成績,機試成績
--沒有成績的學員顯示缺考
select stuName,sex,Age,WriteExam=
case
when WriteExam IS null then '缺考'
else CONVERT(varchar(20),writeExam)
end,
LadExam=
case
when LadExam IS null then '缺考'
else CONVERT(varchar(20),ladexam)
end
from StuInfo si left join Exam e
on si.StuId=e.StuId
--未參加考試的學員成績為0
select stuName ,sex ,ISNULL(age,18),
ISNULL(WriteExam,0),
ladexam=
case
when ladexam IS null then 0
else ladexam
end
from StuInfo si left join Exam e
on si.StuId=e.StuId
(7)索引、視圖、事務
--創建索引
語法:
if exists(select*from sys.indexes
where name='IX_stuinfo_AgeName')
drop index stuinfo.IX_stuinfo_AgeName
go
create nonclustered index 索引名
on 表名(按某列升序或降序)
例子:
create nonclustered index IX_stuinfo_AgeName
on stuinfo(age,stuname desc)
備注:列名后加 desc 是降序的意思,不加默認升序
備注2:nonclustered表示創建非聚集索引 還有如:unique表示創建唯一性索引,clustered 表示創建聚集索引
--使用索引
語法:
select*from 有該索引的表名
with (index=索引名)
例子:
使用索引IX_stuinfo_AgeName 查詢學員信息
select*From StuInfo
with(index=IX_Stuinfo_AgeName)
--索引的優點和缺點
優點:
1、加快訪問速度
2、加強行的唯一性
缺點:
1、帶索引的表在數據庫中需要更多的存儲空間
2、更新數據的命令需要更長的處理時間,因為它們需要對索引進行更新
--創建視圖
語法:
create view 視圖名
as
select 列名 from 表1,表2
where 表1.id =表2.id order by 條件
例子:
創建一個視圖:獲取學員的姓名、性別、年齡、筆試成績、機試成績、並且按筆試成績降序排序
if exists(select*from sys.views
where name='VW_Stu')
drop view VW_Stu --有相同視圖則刪除原視圖
go
create view VW_Stu
as
select top 100 stuName,Sex,Age,WriteExam,LadExam
from StuInfo si,Exam e
where si.StuId=e.StuId
order by WriteExam Desc
go
--視圖的使用
select *from VW_Stu
--事務
事務的ACID屬性
1、原子性
一個事務對數據庫的所有操作,是一個不可分割的工作單元。這些操作要么全部執行,要么什么也不做。保證原子性是數據庫系統本身的職責,由DBMS的事務管理子系統來實現。
2、一致性
一個事務獨立執行的結果應保持數據庫的一致性,即數據不會因為事務的執行而遭受破壞。確保單個事務的一致性是編寫事務的應用程序員的職責。在系統運行時,由DBMS的完整性子系統執行任務。
3、隔離性
在多個事務並發執行時,系統應保證這些事務先后單獨執行時的結果一樣,此時稱事務達到了隔離性的要求,也就是在多個並發事務執行時,保證執行結果是正確的,如同單用戶環境一樣。隔離性是由DBMS的並發控制子系統實現的。
4、持久性
語法:
--開啟事務
begin transaction
declare @error int --定義變量,記錄錯誤
set @error=0 --默認無錯
Update bank set Blance=Blance+5000 where Bname='join'
set @error=@errror+@@ERROR
Update bank set Blance=Blance-5000 where Bname='jack'
set @error=@errror+@@ERROR
if(@error<>0) --如果錯誤號不為零,說明有操作出錯
begin
raiserror('轉賬過程出錯',10,1)
rollback --回滾全部操作
end
else
begin
print '恭喜你,轉賬成功!'
commit --提交所有操作
end
實例:
--轉賬事務,轉賬900
begin tran
declare @err int=0 --聲明一個變量,初值為0
update Bank set Cmoney=Cmoney-900 where Cname='張三'
set @err=@err+@@ERROR
update Bank set Cmoney=Cmoney+900 where Cname='李四'
set @err=@err+@@ERROR
if @err>0 --條件
begin
print'交易失敗,事務回滾!'
rollback
end
else
begin
print'交易成功,事務提交'
commit tran
end
(8)存儲過程
--執行dos命令的存儲過程CMDShell
--在d盤根目錄下創建一個文件夾
execute xp_cmdshell 'md D:\DB'
--查看D盤下的所有信息
exec xp_cmdshell 'dir d:\'
--查看視圖VW_Stu的源代碼
exec sp_helptext 'VW_Stu'
--查看一個表的索引
exec sp_helpindex 'stuInfo'
--查看一個數據庫中的存儲過程
exec sp_stored_procedures
--進行數據庫的邏輯名稱改名(顯示名稱)
exec sp_renamedb BankDBs,BankDB--主文件名是不會變的
--查看當前數據庫中的表和視圖情況
exec sp_tables
--將網格顯示改為文本格式顯示
use StuDB
--創建一個存儲過程
--顯示機試和筆試的平均成績,並且顯示本次考試的成績情況
--還要顯示未通過的學員信息
if exists(select*from sys.procedures
where name='ScoreCountl')
drop procedure ScoreCountl
go
create procedure ScoreCountl
as
declare @write decimal,@lab decimal
select @write=AVG(writeExam),@lab=AVG(LadExam)
from Exam
print '筆試成績:'+convert(varchar(20),@write)
print '機試成績:'+convert(varchar(20),@lab)
if @write>=70 and @lab>=70
print'本班考試成績優秀!'
else
print'本班考試成績一般!'
print'-------------------------------------------------'
print'----------參加本次考試沒有通過的學員名單-----------'
select stuname 姓名,si.StuId 學號,WriteExam 筆試成績,LadExam 機試成績
from StuInfo si,Exam e
where si.StuId=e.StuId and ( WriteExam<60 or LadExam<60)
go
exec ScoreCountl
--自由調控及格線
if exists(select*from sys.procedures
where name='ScoreCount2')
drop procedure ScoreCount2
go
create procedure ScoreCount2
@w decimal=60,--筆試及格線
@l decimal=60 --機試及格線,加了默認值60
as
declare @write decimal,@lab decimal
select @write=AVG(writeExam),@lab=AVG(LadExam)
from Exam
print '筆試成績:'+convert(varchar(20),@write)
print '機試成績:'+convert(varchar(20),@lab)
if @write>=70 and @lab>=70
print'本班考試成績優秀!'
else
print'本班考試成績一般!'
print'-------------------------------------------------'
print'----------本次筆試及格線:'+convert(varchar(20),@w)
+'----------本次機試及格線:'+convert(varchar(20),@l)
print'----------參加本次考試沒有通過的學員名單-----------'
select stuname 姓名,si.StuId 學號,WriteExam 筆試成績,LadExam 機試成績
from StuInfo si,Exam e
where si.StuId=e.StuId and ( WriteExam<@w or LadExam<@l)
go
exec ScoreCount2 @l=40,@w=60 --分別為機試和筆試的及格線
exec ScoreCount2 --有默認值的情況下
use GoodSystem
--創建一個存儲過程:查詢生產日期為某年的
--商品名稱,類型,生產日期,庫存
if exists(select*from sys.procedures
where name='ScoreCount3')
drop procedure ScoreCount3
go
create procedure ScoreCount3
@d decimal
as
select Name 商品名稱,gt.Type 類型,ProductionDate 生產日期,Amount 庫存
from GoodS gs,GoodType gt
where gs.Tid=gt.Tid and year(ProductionDate)=@d
--查詢2017年的商品信息
go
exec ScoreCount3 2017
--創建一個存儲過程:查詢類型為‘食品’的商品信息
if exists(select*from sys.procedures
where name='ScoreCount4')
drop procedure ScoreCount4
go
create procedure ScoreCount4
@s varchar(20)
as
select Name 商品名稱,gt.Type 類型,ProductionDate 生產日期,Amount 庫存
from GoodS gs,GoodType gt
where gs.Tid=gt.Tid and gt.Type=@s
go
exec ScoreCount4 '食品'
(9)帶輸出參數的存儲過程
--創建一個存儲過程:添加一個學員成績信息
if OBJECT_ID('InsertExam') is not null
drop proc InsertExam
go
create proc InsertExam
@ExamNo int,
@stuid varchar(50),
@writeExam decimal(10,2),
@ladExam decimal(10,2),
@n int output
as
insert Exam(ExamNo,StuId,WriteExam,LadExam)
values(@ExamNo,@stuid,@writeExam,@ladExam)
select @n=@@ROWCOUNT
go
select*from Exam
--調用添加存儲過程
declare @n int
exec InsertExam '8','1006',70,80,@n output
if @n>0
print'添加成功'
else
print'添加失敗'
use MySchool
select*from Teacher
--引用到C#案例MySchool_Proc
--添加教員
if OBJECT_ID('InsertTeacher') is not null
drop proc InsertTeacher
go
create proc InsertTeacher
@LoginId varchar(50),
@LoginPwd varchar(50),
@TeacherName varchar(50),
@Sex varchar(50),
@UserStateId int,
@Birthday dateTime,
@n int output
as
insert Teacher(LoginId,LoginPwd,TeacherName,Sex,UserStateId,Birthday)
values(@LoginId,@LoginPwd,@TeacherName,@Sex,@UserStateId,@Birthday)
select @n=@@ROWCOUNT
go
--修改教員
if OBJECT_ID('UpdateTeacher') is not null
drop proc UpdateTeacher
go
create proc UpdateTeacher
@LoginId varchar(50),
@LoginPwd varchar(50),
@TeacherName varchar(50),
@Sex varchar(50),
@UserStateId int,
@Birthday dateTime,
@n int output
as
update Teacher set LoginPwd=@LoginPwd, TeacherName=@TeacherName,
Sex=@Sex,UserStateId=@UserStateId,Birthday=@Birthday
where LoginId=@LoginId
select @n=@@ROWCOUNT
go
--刪除教員
if OBJECT_ID('DeleteTeacher') is not null
drop proc DeleteTeacher
go
create proc DeleteTeacher
@LoginId varchar(50),
@n int output
as
delete from Teacher where LoginId=@LoginId
select @n=@@ROWCOUNT
--自我理解
--添加、修改、刪除存儲過程都是為了應用到C#程序中可以更快的執行,且占系統運行內存不多。
--C#中的調用其實就是一個三層架構
