sql基本语句代码总结.docx
《sql基本语句代码总结.docx》由会员分享,可在线阅读,更多相关《sql基本语句代码总结.docx(14页珍藏版)》请在冰豆网上搜索。
![sql基本语句代码总结.docx](https://file1.bdocx.com/fileroot1/2022-12/7/69ae4e36-7419-43b3-9c78-3bf2ce0e0e85/69ae4e36-7419-43b3-9c78-3bf2ce0e0e851.gif)
sql基本语句代码总结
1.创建sql语句
Createdatabasemydb
on
(
Name=mydb_dat,
Filename=’f:
\data\mydb_dat.mdf’,
Size=5mb,
Maxsize=20mb,
Filegrowth=5%
)
Logon
(
Name=mydb_log,
Filename=’f:
data\mydb_log.ldf’,
Size=5mb,
Maxsize=20mb,
Filegrowth=1mb
)
2.可以创建同一个文件组,组名默认为PRIMARY,数据文件可以存放在不同磁盘上,数据库中的数组是分布在所有的次要文件中
createdatabaseMyDB
onprimary
(
name=mydb_dat,
filename='f:
\data\mydb_dat.mdf',
size=6MB,
maxsize=20mb,
filegrowth=5%
),
filegroupdbfg
(
name=dbfg_dat1,
filename='d:
\data\mydb_dat1.ndf',
size=5mb,
maxsize=20mb,
filegrowth=5%
),
(
name=dbfg_dat2,
filename='e:
\data\mydb_dat2.ndf',
size=5mb,
maxsize=20mb,
filegrowth=1mb
)
logon
(
name=mydb_log,
filename='f:
\data\mydb_log.ldf',
size=5MB,
maxsize=20mb,
filegrowth=5%
)
3.修改数据库名alterdatabasemydbmodifyname=youdb
存储过程修改数据库名
execsp_dboption'youdb','single',true
execsp_renamedb'youdb','mydb'
execsp_dboption'mydb','single',false
4.修改数据库文件大小
Usemaster
Alterdatabasemydb
Modifyfile
(
Name=mydb_dat,
Size=6mb,
Filegrowth=1%
)
5.增加数据库文件组
Usemaster
Alterdatabasemydb
Addfile
(
Filename=’f:
\data\mydb_data1.ndf’,
Name=mydb_dat1,
Size=6mb,
Filegrowth=1%
)
6.删除数据库dropdatabasemydb
7.从sql中删除,但保持其数据和事务日志文件(相当于分离数据库)
Execsp_detach_dbmydb
8.附加数据库
Execsp_attach_dbmydb,’f:
\data\mydb_dat.mdf’
9.备份数据库
Backupdatabasemydbto
Disk=’f:
\data\database_bak.dat’withname=’backup’
10.还原数据库
restoredatabasemydbfromdisk=’f:
\data\database_bak.dat’withreplace
11.创建数据库快照
createdatabasemydb001
On
(name=’mydb_dat’,
Filename=’f:
\data\mydb001.mdf’
),
(name=’ddd’,--这是次要文件可以没有
Filename=’f:
\ddd.ndf’
)
Assnapshotofmydb
12.恢复数据库快照
restoredatabasemydbfromdatabasesnapshot=’mydb001’
13.查看日志dbcclog(数据库名,n)
N的值
0-最少信息(operation,context,transactionid)
1-更多信息(plusflags,tags,rowlength)
2-非常详细的信息(plusobjectname,indexname,pageid,slotid)
3-每种操作的全部信息
4-每种操作的全部信息加上该事务的16进制信息
默认type=0
1.创建用户自定义类型
sp_addtype{type_name},[base_type],[[‘null’|’notnull’]],[‘拥有者’]
删除sp_droptypetype_name
2.在MMM数据库中创建自定义数据类型
execsp_addtypenametype,’varchar(20)’,’notnull’
删除sp_droptypenametype
3.创建临时表l临时表在退出其作用域是由系统自动删除
createtable#mytemptable一个#的为本地临时表
(
Colaint
)
createtable##mytemp两个##的为全局临时表
(
Colaint
)在tempdb库中查看临时表信息
4.创建、删除表
创建表sales包含以下字段
order_no不能空
Ordr_date不能为空
Ship_date不能为空
useprojects
Createtablesales
(
Order_nointnotnull,
order_datedatetimenotnull,
Ship_datedatetimenotnull
)
更改表名
Execsp_renamesalesssaless
删除表
droptablesales
5.①.创建函数列的表
Createtabletesttable
(
Indateasgetdate(),
Idint,
Usenameasuser_name()
)
②.用户定义类型列创建计算列
createtabletestable
(
idintnotnull,
Col1nametype
)
③.表变量
declare@ttable
(col1int,
col2varchar(10)
)
Insertinto@tvalues(1,’很好’)
查询select*from@t
6.修改表employee
添加列:
电话号码telephone_no
添加列:
字符列email为char
修改列类型:
email为varchar
修改列空为非空列
修改字段名:
删除列:
删除email列
altertableemployee
Addtelephoneintnull,
Emailchar(29)null
Altertableeemployee
altercolumnemailvarchar(20)null
altertableemployee
altercolumnemailvarchar(20)notnull
execsp_rename“构架名.表名.旧字段名’,’新字段名’,’column’
altertableemployee
dropcolumnemail
7.约束
①.主键约束
创建是加主键
createtablecustomers
(
customernointidentitynotnullprimarykey,
Customernamevarchar(30)notnull
)
在现有表中添加主键
altertablecustomers
Addconstraintpk_customerno
Primarykey(customerno)
②.外键约束
使用外键床架一个表
Createtableorders
(
Orderedintidentitynotnullprimarykey,
Customernointnotnullforeignkeyreferencescustomers(customerno)
)
在已存在的表中添加外键
altertableorders
addconstraintfk_employeeCreatesorders
Foreignkey(customerno)referencescustomers(customerno)
③.级联动作
createtableOrderDetails
(
orderidintnotnull,
partnovarchar(10)notnull
constraintPKOrderDetails
primarykey(orderid,partno),
constraintFKOrderContrainsDetails
Foreignkey(OrderID)
Referencesorders(orderid)
onupdatenoaction
ondeletecascade
)
④.唯一约束
在创建表时创建唯一约束
createtalbeshippers
(
Shipperidintidentitynotnullprimarykey,
Phonenovarchar(14)notnullunique
)
在已存在的表中创建唯一约束
altertableshippers
Addconstraintak_shippersphonenounique(phoneno)
⑤.Check约束
altertablecustomers
Addconstraintcn_customerdateinsystem
check
(dateinsystem<=getdate())
删除check约束
altertabletestable
Dropconstraintcn_customerdateinsystem
⑤.Default约束
创建默认表
createtableshippers
(
Shipperidintidentitynotnullprimarykey,
Dateinsystemsmalldatetimenotnulldefaultgetdate()
)
在已存在的表上加上默认值
altertablecustomers
addconstraintcn_customerdefaultdateinsystem
Defaultgetdate()fordateinsystem
1.表数据插入
使用Insert插入
USEnorthwind
INSERTintocustomers(customerid,companyname,contactname,contacttitle,address,city,region,postalcode,country,phone,fax)
VALUES(‘PECOF’,‘PecosCoffeeCompany’,’MichaelDunn’,’Owner’,‘1900OakStreet’,‘Vancouver’,‘BC’,’V3F2K1’,‘Canada’,’(604)555-3392’,’(604)555-7293’)
使用insert和select插入行
USEnorthwind
INSERTcustomers
SELECT
substring(firstname,1,3)
+substring(lastname,1,2),lastname,firstname,title,address,city,region,postalcode,country,homephone,NULL
FROMemployees
使用selectinto插入
USEnorthwind
SELECTproductnameASproducts,unitpriceASprice,
(unitprice*0.1)AStax
INTO#pricetable
FROMproducts
使用top插入
USEnorthwind
SELECTtop10
productnameASproducts,unitpriceASprice,
(unitprice*1.1)AStax
INTO#pricetable
FROMproducts
Select*from#pricetable
2.插入部分数据
USEnorthwind
INSERTshippers(companyname)
VALUES(‘Fitch&Mather’)
SELECT*FROMshippers
WHEREcompanyname=‘Fitch&Mather’
3.使用delete语句
USEnorthwind
deleteshippers
WHEREcompanyname=‘Fitch&Mather’
4.使用truncatetable
删除表中所有的行,但保留表的结构和与之相关的对象
TRUNCATETABLE语句比DELETE语句执行速度快
如果表中有IDENTITY列,TRUNCATETABLE语句会重新设置原始数据
USEnorthwind
TRUNCATETABLEorders
5.删除基于其他表的行
DELETE[FROM]{表名|视图名}
[FROM{<表资源>}[,…n]]
[WHERE搜索条件]
6.根据表中数据更新
usenorthwind
Updateproducts
Setunitprice=(unitprice*1.5),列名=新值
7.表操作
UseAdventureWorks
Select*fromproduct
UseAdventureWorks
Selectname,productnumber,reorderpointfromproduct
8.使用字符串比较符
通配符
描述
%
0或多个字符串
_
任何单个的字符
[]
在指定区域或集合内的任何单个字符
[^]
不在指定区域或集合内的任何单个字符
USEnorthwind
SELECTcompanyname
FROMcustomers
WHEREcompanynameLIKE'%Restaurant%'–其中包含restrurant
9.使用逻辑运算符
优先级notandor
USEnorthwind
SELECTproductid,productname,supplierid,unitprice
FROMproducts
WHERE(productnameLIKE'T%'ORproductid=16)
AND(unitprice>16.00)
10.检索一定范围内的值
USEnorthwind
SELECTproductname,unitprice
FROMproducts
WHEREunitpriceBETWEEN10AND20
11.使用值列表作为搜索条件
USEnorthwind
SELECTcompanyname,country
FROMsuppliers
WHEREcountryIN('Japan','Italy')
12.检索未知值
USEnorthwind
SELECTcompanyname,fax
FROMsuppliers
WHEREfaxISNULL
13.对数据进行排序asc为正序desc为倒序
usenorthwind
select*fromemployeesorderbyfirstnameasc(desc)
14.消除重复行
USEnorthwind
SELECTDISTINCTcountry
FROMsuppliers
ORDERBYcountry
15.使用topN
USEnorthwind
SELECTTOP5productname,unitprice
FROMproducts
SELECTTOP5PERCENTproductname,unitprice
FROMproducts
16.使用聚合函数
例子:
USEnorthwind
SELECTproductid,
SUM(quantity)ASQuantitySum
from[orderdetails]
GROUPBYproductid
ORDERBYproductid
17.使用HAVING子句时,应注意
只在使用GROUPBY子句的同时,使用HAVING子句来限制分组
可以引用任何出现在选择列表中的字段
不要联合使用关键字ALL和HAVING子句。
因为HAVING子句会忽略ALL关键字,并返回只符合HAVING条件的组
groupby分组
USEnorthwind
SELECTproductid,
SUM(quantity)ASQuantitySum
from[orderdetails]
GROUPBYproductid
HAVINGSUM(quantity)>500
ORDERBYSUM(quantity)
18.连接
内部连接是连接类型中最普通的一种,与大多数连接一样,内部连接根据一个或几个相同的字段将记录匹配在一起,但是内部连接仅仅返回那些存在的字段匹配的记录
Usenorthwind
selectproducts.*,suppliers.supplieridfromproductsinner
joinsuppliersonproducts.supplierid=suppliers.supplierid
usepubs
selecta.au_lname+','+a.au_fnameasauthor,t.titlefromauthorsa
jointitleauthortaona.au_id=ta.au_idjointitlestont.title_id=ta.title_id
外部连接时必需跟上左侧连接还是右侧连接
Usepubs
selectdiscounttype,discount,s.stor_namefromdiscountsd
leftouterjoinstoressond.stor_id=s.stor_id
selectdiscounttype,discount,s.stor_namefromdiscountsd
rightjoinstoressond.stor_id=s.stor_id
完全连接
Usepubs
selectdiscounttype,discount,s.stor_namefromdiscountsd
fulljoinstoressond.stor_id=s.stor_id
交叉连接
Usepubs
selectdiscounttype,discount,s.stor_namefromdiscountsd
crossjoinstoress
Union连接
usenorthwind
selectcompanyname,
address,
city
fromcustomers
union
selectcompanyname,
address,
city
fromsuppliers
IN
usenorthwind
select*fromcustomerswherecustomeridin
(selectdistinctcustomeridfromorders)
Exists
usenorthwind
select*fromorderswhere
Exists(select*fromcustomerswherecustomerid='alfki')