SQLServer2005 高校教學語句

SQLServer2005 高校入門教學系列

SQL 語句基礎code

--查詢學生中選修課程號 爲1 的學生姓名

select sname 
from student
where exists(
    select *
    from sc    
    where student.sno = sc.sno
    and cno='1'
)

--查詢選修了所有課程的學生姓名

select sname
from student
where exists(
    select *
    from course
    where  exists(
        select *
        from sc    
        where sc.cno = course.cno
                and sc.sno = student.sno
    )
)

-- 左值連接, 外連接


select student.sno,sname,ssex,sage,sdept,cno,grade
from student left outer join sc on (student.sno = sc.sno)


--創建惟一性索引

create unique index stu on student(sno asc,cno desc)


--having 表明着選擇條件
select sno from sc group by sno 
having sno <> '200215121'

-- 修改數據表字段類型

alter table student alter column comment char(255)

alter table sc alter column grade smallint

-- 添加數據表列

alter table student add comment char(50)

alter table student add S_enterence datetime

alter table course add unique(cname)

-- 模糊精確條件

select *
from course
where cname like 'DB\_design' escape '\'

--查詢課程名中含有DB_design的課程名


--創建存儲過程

create procedure proc_insert_student
    @sno1 char(9),
    @sname char(20),
    @ssex char(2) = '男',
    @sage int,
    @sdept  char(20)
as 
begin
    insert into student(sno,sname,ssex,sage,sdept) 
    values(@sno1,@sname,@ssex,@sage,@sdept)
end

create proc proc_avgrade_sc
@sno char(9),
@savg int output  -- out
as 
begin
    select @savg = avg(grade)
    from sc where sno = @sno 
end


--執行存儲過程
 exec proc_insert_student '2002015126','張新陽','男',19,'CS'
 exec proc_insert_student @sno1 = '2002015128',@sname = '尼陽',@sage = 22,@sdept = 'IS'


declare @avg int
 set @avg = 0
 exec proc_avgrade_sc '200215121',@avg output  

--輸出參數必須是output 類型
--select @avg 平均成績

--刪除存儲過程
drop prodc [procedure_name]
相關文章
相關標籤/搜索