Sql Server語句大全

T-SQL語句大全
--跳轉到SQL myDemo
USE [SQL myDemo]
 go
 
 --聲明變量id
 declare @id int
 --爲變量賦值:直接賦值
 set @id = 2
 --將cid爲3的cname值賦給變量@cn
 declare @cn varchar(10) 
 --爲變量賦值:查詢賦值
 select @cn = cname from classes where Cid = @id
 --輸出【print:可直接輸出'字符串'或變量】變量@cn  if{} ===》if begin end
 print @cn
 
 --SQL Server的版本信息
 print '版本信息 = '+ @@version
 
 --配置數據庫,啓動監聽服務(SQL2008)【當監聽的指定數據庫內容某張表變化時就更新緩存】
 alter database [SQL myDemo] set new_broker with rollback immediate
 alter database [SQL myDemo] set enable_broker
 
 --檢測數據庫是否開啓監聽服務【結果爲0則是未啓動,爲1是啓動狀態。數據源緩存使用】
 select is_broker_enabled as 是否啓動 from sys.databases where name = 'SQL myDemo'
 
 --生成GuId
 select newid()

select top(3) * from students where sid not in (select top(3) sid from students)

 select ID,Name,Age from T_GUID
 INSERT INTO T_GUID (ID,NAME,AGE)
 select NEWID(),'王巖',21 union
 select NEWID(),'鵬哥',22 union
 select NEWID(),'馬金龍',23
 
 select * from students where cid is null
 
 select * from rpater
 delete from rpater where id <> 1 and id <> 2 and id <> 4 and id <> 5
 insert into classes(cnum,cname,clog) values (23,'五年級','吼吼')
--查詢表數據
select * from dbo.students where SID = 120 and sAge = 23
--SQL注入:執行sql語句過程當中,將sql語句進行拼接時含有攻擊性的字符,致使數據泄漏
select * from stuInfffo where stuName = '' or 1 = 1 
update stuInfffo set stuname = '王巖',stuno = 55,stuSex = '' where stuname = '王巖'
select * from students where SID = 120
select * from students where sname 
select * from classes
select top(3) * from classes where cid not in (select top(3) cid from classes)
select top(3) * from classes where cid not in (select top(4) cid from classes)
--select top(3) cid from classes where cid > (select max(cid) from (select top(4) cid from classes) as classses)
select top(3) * from classes where cid > (select top(1) cid from classes where cid not in (select top(3) cid from classes))
select top(4) * from classes order by cid desc
select cid from classes where cnum = (select max(cnum) from classes)

select * from classes where cid between 5 and 7
select sum(sid) from students where cid = 2
select * from commodity where 類別 like '礦%'
update students set sName='楊洋',sAge=23,sLovely='籃球' where SID=120

--插入單行數據
--語法:insert into 表名(列名) values (值)
insert into dbo.Students(sName,sAge,slovely,sclass,cid) values('馬金龍',21,'籃球',02,2)


--插入多行數據
--語法:insert into 表名(列名)
--        select 值 union
--        select 值 
insert into dbo.Students(sName,sAge,sClass,sLovely)
select '張星遠',22,'02','籃球' union
select '趙赫然',22,'02','籃球'

--將table1中的id,name值添加到table2中
--table1:id,name,set,address
--table2:id,name
insert into table2(id,name)
select id,name from table1 where id != 100

--修改數據語法:update 表名 set 列='修改值' where 條件
update dbo.Students set sName='楊洋'  where SID = 105
update dbo.Students set sAge=24 where sName='鵬哥'
update dbo.Students set sClass='01' where SID = 100 or SID = 101

--刪除數據語法:delete from 表名 where 條件
delete from dbo.Students where SID = 109 or SID = 110
delete from dbo.Students where 113 <= SID and SID <= 115
--刪除表中全部數據[清空表數據時效率更高],不能加任何條件
truncate table students


--查詢數據語法:select * from 表名
select * from dbo.Students

--查詢爲空的行
select * from dbo.Students where Cid is null

--is(是),查詢不爲空的行
select * from dbo.Students where Cid is not null

--as(重命名)
select sname as 姓名 from dbo.Students

--使用 = 賦值
select '姓名' = sname+'.'+cname from dbo.Students,dbo.Classes

--限制查詢:top(n)
select top(2) * from dbo.Students --查詢前兩行
select top 50 percent * from students --按百分比查詢,查詢表前百分之五十的內容

--排序(小到大)
select * from dbo.Students order by sAge

--分組
select sname,COUNT(sname) as 次數,MAX(sid) as 最大ID from Students group by sname having COUNT(sname) > 2
select sname,count(*) from students group by sname having count(sname) > 2

--倒序(大到小):desc
select * from classes order by cid desc

--同時排序多個
select * from dbo.Students order by sAge,sName

--返回當前日期
select GETDATE()

--返回你所登錄的計算機的名字
select HOST_NAME()

--替換字符串
update dbo.Students set sName = replace('鵬張','','')where SID = 101
update dbo.Students set sClass = replace(sclass,'0','00')

--模糊查詢:like
select * from dbo.Students where sName like '張%'

--模糊查詢實現文字聯想功能(例:百度搜索提示原理)
select * from students where sname like '%[鵬龍]%'

--in:查詢指定字符的內容
select * from Classes where cLog in('哈哈')

--between特定範圍查詢
select * from dbo.Students where SID between 116 and 118

--總和查詢:sum
select MAX(cname) as '班級', sum(cnum) as '總人數' from Classes 

--平均數:avg
select avg(cnum) as '平均人數' from Classes

--最大值:max
select max(cname) as '最大人數班級' from Classes

--最小值:min
select min(cname) as '最大人數班級' from Classes

--查詢總行數:count
select count(*) as '總行數' from Classes 

--查詢數據庫中全部表的表名
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'

--刪除、增長、修改數據表其中的一列
alter table Ware Drop column wBak  -- 刪除
alter table Ware Add wBak nvarchar(MAX) null default '老馬' -- 增長。default 默認值
alert table ware alert column Name varchar(10) --修改字段

--插入一條數據,用最快的方式查詢出該數據的ID
insert into students(sName,sAge,sLovely,sClass,Cid) values('張三',23,'足球',2,3) select ident_current('students')
insert into students(sName,sAge,sLovely,sClass,Cid) values('張三',23,'足球',2,3) select @@identity

delete from students sid not in (select min(sid) from students group by sname having count(sname) > 1)
select * from students
select * from classes
--聯結查詢:內聯結(inner join:查詢全部條件相同的內容)左聯結(left join:左全右偏)右聯結(right join:右全左偏)
--【 on 至關於 whereselect * from Students inner join Classes on Students.Cid = Classes.Cid and students.sid = 146
select * from Students left join Classes on Students.Cid = Classes.Cid
select * from Students right join Classes on Students.Cid = Classes.Cid
select * from Students cross join Classes where Students.Cid = Classes.Cid --交叉聯結(同內聯結)
select * from Students full join Classes on Students.Cid = Classes.Cid     --完整外聯結

--三表聯結查詢
select * from Students as s,Classes as c,demos as d where s.Cid = c.Cid and s.sid = d.sid
--查詢「鵬哥」所借的書籍的信息
select c.cnum,c.cname from students as s, classes as c,demos as d where  d.id = c.id and s.sname = '鵬哥'
--分組查詢
select sAge,COUNT(sAge) as 年齡個數 from Students group by sAge having COUNT (sAge) > 0 
select sAge as 年齡 from Students group by sAge
select sname,COUNT(sname) as 次數,MAX(sid) as 最大ID from Students group by sname having COUNT(sname) > 2
select * from students, (select sname,COUNT(sname) as 次數,MAX(sid) as ID from Students group by sname having COUNT(sname) > 2) as a where students.sID <> 129 AND students.sname = '馬金龍' --s.sid AND s.sid = a.ID


select sage from students group by sage
select sname,COUNT(sname) from students group by sname having count(sname) > 1
delete top(2)  from students where sid not in (select top(10) sid from students)
select id from rpater where name = '張三'
delete from demos where sid = 117
select * from demos where cname = '五年三班'
select * from Classes inner join demos on Classes.cname = demos.cname
select * from demos where sid = 116
select * from t_Dropdown1 as d,t_Dropdown2 as r,t_Dropdown3 as o where d.id = r.pid and r.pid = o.pid
delete from rpater where id > 5
select * from students where sName = '張三'
select sname from students
insert into students(sname,sage,slovely,sclass,cid)
select '王巖',21,'籃球',2,2 union
select '趙帥',21,'籃球',2,2 union
select '張鵬',21,'籃球',2,2 union
select '鵬哥',21,'籃球',2,2 union
select '馬金龍',21,'籃球',2,2 union
select '馬金龍',21,'籃球',2,2 union
select '王巖',21,'籃球',2,2 union
select '馬金龍',21,'籃球',2,2 union
select '張鵬',21,'籃球',2,2 

insert into T_ChuanZhiBoKe(Name,Pwd,ErrorTimes,ErrorTime) values('張三','789',2,(getdate()))
select * from T_ChuanZhiBoKe
update T_ChuanZhiBoKe set ErrorTimes = ErrorTimes + 1,ErrorTime = (getdate()) where id = 3
update T_ChuanZhiBoKe set ErrorTime = (getdate()) where id = 2

--取得表中不重複的值
select * from students where sid  in (select max(sid) from students group by sName)

--刪除表中name重複的值,只留一條
delete from students where sid not in (select min(sid) from students group by sname)

--查詢表A(id,name)中name重複三次以上的記錄,並刪除重複記錄,只留id最大的
delete from students where sname in (select sname from students group by sname having count(sname) > 1) and sid not in (select max(sid) from students group by sname having count(sname) > 1)

select * from stuInfffo 
--查詢和學號’s25301’的這位同窗性別相同的全部同窗的姓名和年齡
select stuname,stuAge from stuInfffo where stuSex in (select stusex from stuInfffo where stuno = 's25301')
--查詢時間差
SELECT DATEDIFF(MONTH,'2012-01-01 0:0:0',getdate())




select top(2) * from students where sid > (select max(sid) from (select top(6) sid from students) as a)
select top(2) * from classes where cid not in (select top(5) cid from classes)
delete from classes where cid in (select top(2) cid from classes where cid not in (select top(5) cid from classes))
View Code

--建立包含父級子級的表,查詢顯示爲父級-子級-子級;父級-子級-子級sql

select *,
        case
            when PID = 0 then ID
            else PID
        end
as TID FROM MianShiTi ORDER BY TID,PID

select * from MianShiTi
View Code

--自定義函數【標量函數;內嵌表值函數;多聲明表值函數】:
        --能在select等語句中直接使用自定義函數,存儲過程不行;
        --自定義函數能夠調用其它函數,也能夠調用本身( 結果集須要經過遞歸等方法獲得時,可使用函數,函數比較靈活);
        --只查詢,不能修改數據庫的狀態
        --只能調用擴展存儲過程,但在sqlserver2008的後續版本將再也不支持擴展存儲過程shell

create function biaoliang(@age int,@cid int)
returns int
as
begin
    return @age * @cid
end
go
--自定義函數的調用【SQL myDemo:數據庫名稱】
select [SQL myDemo].dbo.biaoliang(23,2)
View Code

觸發器數據庫

if(object_id('tgr_students_insert','tr') is not null)--判斷是否有名稱爲tgr_students_insert的觸發器
    drop trigger tgr_students_insert                 --若是有則刪除該觸發器
go
alter trigger tgr_students_insert                     --建立觸發器tgr_students_insert
on students                                            --當對students表進行insert插入操做時執行as以後的T-SQL語句
    for insert
as
    declare @id int,@name varchar(20),@temp int;    --聲明局部變量
    select @id = sid,@name = sname from inserted;    --插入語句時生成一張數據庫臨時表(inserted),將新插入語句的sid,sname值賦給變量@id,@name
    set @name = @name; -- + convert(varchar,@id);    --從新賦值
    set @temp = @id / 2;
    insert into classes values(18,@name,@temp,@id);    --向students表內插入語句時同時向classes表插入一條語句
    print '添加學生成功!';
go

insert into students(sname,sage,slovely,sclass,cid) values('張三',23,'CS',2,2)
View Code

索引:緩存

USE [SQL myDemo]
GO
if exists(select name from sysindexes where name = 'LX_suoyin')
drop index students.LX_suoyin
create NONCLUSTERED index LX_suoyin
on students(sage)
WITH FILLFACTOR= 30
GO
select * from students with(index=LX_suoyin) where sage between 21 and 23
View Code

橫表縱表相互轉換ide

--縱錶轉換橫表
select * from TableA

select Name,  -- 遍歷每列學生
sum(case Course
        when '語文' then Grade  -- 若是科目是語文則返回語文成績,不然返回0
        else 0 
    end) as 語文,
sum(case Course
        when '數學' then Grade 
        else 0 
    end) as 數學,
sum(case Course 
        when '化學' then Grade 
        else 0 
    end) as 化學,
sum(case Course 
        when '物理' then Grade 
        else 0 
    end) as 物理,
sum(case Course 
        when '外語' then Grade 
        else 0 
    end) as 外語
from TableA group by Name

--橫錶轉縱表
select '外語',外語 from TableB

select Name,'語文' as 科目, 語文 as 成績 from TableB union all
select Name,'數學' as 科目, 數學 as 成績 from TableB union all
select Name,'外語' as 科目, 外語 as 成績 from TableB          -- '外語' as 科目 至關於 將分數轉換爲外語科目 
ORDER BY Name,科目 DESC                                          -- 外語 as 成績 等於把外語字段轉換爲成績字段
View Code

縱表函數

橫表sqlserver

建庫建表建約束 ====== 視圖spa

--建立數據庫
if exists(select * from sys.databases where name='stulan')
drop database stulan
create database stulan
on 
(
    name = 'stulan_data',
    filename = 'E:\項目練習\stulan_data.mdf',
    size = 3mb,--初始大小
    maxsize = 50mb,--文件增加的最大值
    filegrowth = 5mb--文件增加率
)
go
--建立表
use stulan
go
if exists(select * from sys.objects where name='t_stoInfo')
drop table t_stoInfo
go
create table t_stoInfo
(
    id int identity(1,1) not null,--自增列
    name varchar(20) not null,
    age int not null,
    [address] varchar(max) not null,
    stuNo char(6) not null
)
go
--建立表
if exists(select * from sys.objects where name='t_stuMarks')
drop table t_stuMarks
go
create table t_stuMarks
(
    id int identity(1,1) not null,
    stuNo char(6) not null,
    shuxue varchar(20) null,
    yuwen varchar(20) null
)
go

--建立約束
--主鍵約束:要求主鍵列數據惟一,而且不容許爲空
alter table t_stoInfo
add constraint pk_stuNo primary key(stuNo)

--默認約束:某列的默認值
alter table t_stoInfo
add constraint df_address default('地址不詳') for address

--檢查約束:某列的取值範圍限制
alter table t_stoInfo
add constraint ck_age check(age between 15 and 50)

--惟一約束:要求該列惟一,容許爲空,但只能出現一個空值
alter table t_stoInfo
add constraint uq_id unique(id)

--外鍵約束:用於兩表間創建關係,須要指定引用主表的那列
alter table t_stuMarks
add constraint fk_stuNo foreign key(stuNo) references t_stoInfo(stuNo)
go

--事務
begin transaction -- 開始事務
declare @errorsum int --定義變量
set @errorsum = 0 --初始化變量
update Students set sAge = sAge + 12 where sName = '張鵬'
set @errorsum = @errorsum + @@error --累計是否有錯誤

if @errorsum <> 0
begin
    print '錯誤'
    rollback transaction --回滾事務
end
else
begin
    print '正確' 
    commit transaction --提交事務
end
select * from Students 


--建立視圖
create view view_Display
as 
select stuName,stuNo,(select writtenExam from stuMarks where stuMarks.stuNo = stuInfffo.stuNo) as writtenExam
 from stuInfffo

EXEC sp_tables
EXEC sp_columns students

EXEC xp_cmdshell 'dir d:\'

alter proc proc_lantian
@cNum int,
@cName varchar(10),
@cLog varchar(10)
as
select @cNum = cNum,@cName = cname,@cLog = clog from classes

  EXEC('select clog from classes')
go

alter proc proc_lantian
@status int,  --接收操做參數
@outSta int output  --傳出參數
as
begin
    if @status=1
        begin
        select*from students
        end
    else
        if @status=2
            begin
            select*from classes
            end
    set @outSta = @status
    EXEC proc_lantian @outSta = 1
end 


select * from classes
View Code

分頁存儲過程code

alter proc proc_zp
@a int,--每頁幾條
@b int --第幾頁
as
select top(@a) * from fenye where id not in(select top(@a*@b) id from fenye)
GO
EXEC proc_zp 4,0
View Code

存儲過程實例server

--根據不一樣的參數查詢不一樣的表
alter proc proc_lantian
@tablename varchar(20)
as
declare @str varchar(max)
set @str = N' select * from ' + @tablename
EXEC(@str)
GO
EXEC proc_lantian 'classes'


--根據不一樣的參數查詢不一樣的列及設置條件
alter proc proc_lantian
@columnname varchar(20) = N' * ',
@table varchar(20),
@where varchar(20)=''
as
declare @col varchar(max),@cc varchar(max)
set @cc = N' where ' + @where
if @where = ''
    begin
         set @cc = '' 
    end
set @col = N' select ' + @columnname + N' from ' + @table + @cc
EXEC(@col)
GO
EXEC proc_lantian @table = 'students',@where = 'sid = 120'


-----------------------------------------------------------------
alter proc proc_lantian
@columnname varchar(20) = N' * ',
@rows varchar(50),
@where varchar(100),
@orderrows varchar(50),
@orderbyte int
as
declare @col varchar(max),@cc varchar(max)
set @cc = N' where ' + @where
if @where = ''
    begin
         set @cc = '' 
    end
set @col = N' select ' + @columnname + N' from ' + @table + @cc
EXEC(@col)
GO
EXEC proc_lantian @table = 'students',@where = 'sid = 120'


select * from classes where Cid > 2
select * from T_Readers


alter proc proc_reader
@Name varchar(10)
--@BookNum int
as
--select BookNum from T_Readers where readerName = @Name
    if (select BookNum from T_Readers where readerName = @Name) = 0
        begin
            print('該同窗沒有借閱')
        end
    else
        begin
            select readerName,StudentNum,TeleNum,BookNum from T_Readers where readerName = @Name
        end
GO
EXEC proc_reader '鵬哥'

select * from [User]
alter proc proc_Login
@User varchar(20),
@Pwd varchar(20)
--@ID int
as
    select * from [User] where mName = @User and mPwd = @Pwd
    --delete from [User] where mID = @ID
Go
EXEC proc_Login '徐囡','1122'


--查詢表中同窗姓名,若是存在返回1,不然返回0
alter proc proc_Name
@Name varchar(10)
as
declare @cou int
set @cou = (select count(*) from students where sname = @Name)
    if @cou > 0
        begin
            print(1)
        end
    else
        begin
            print(0)
        end
GO
EXEC proc_Name ''

------
alter proc proc_shuchu
@shuchu int output
as
 select count(*) from students
GO
EXEC proc_shuchu @shuchu output
View Code
相關文章
相關標籤/搜索