sql 基本操作语句

--设置当前数据库是master
use master
go
--查看是否存在Note数据库
if exists(select * from sysdatabases where name='MyNoteBook')
drop database MyNoteBook  
create database MyNoteBook 
on primary
(
name='MyNoteBook_data',
filename='e:\5-25\MyNoteBook_data.mdf',
size=5mb,
maxsize=100mb,
filegrowth=15%
)
log on
(
name='MyNoteBook_log',
filename='e:\5-25\MyNoteBook_log.ldf',
size=2mb,
filegrowth=1mb
)
go

--设置当前数据库是MyNoteBook
use MyNoteBook
go
--查看是否存在UserInfo表
if exists (select * from sysobjects where name='UserInfo')
--删除表
drop table UserInfo
--创建表
create table UserInfo
(
 uID int identity not null,--idetity,自动编号(标识列),从1开始递增
 userName varchar(50) not null,
 uPassword varchar(50) not null,
 uAge int not null,
 uGender varchar(10) not null,
 uIDNummer varchar(18) not null,
)
go
--查看是否存在
if exists (select * from sysobjects where name='PasswordBook')
--删除表
drop table PasswordBook
create table PasswordBook
(
 pID int identity not null,
 pUID int not null,
 pUserName varchar(50) not null,
 password varchar(50) not null,
 pWebsite varchar(200),
 pBindMail varchar(200)
)
go

------------------添加约束------------------
--alter table 表名
--add constraint 约束名(约束类型_约束字段) 约束类型 具体的约束说明
--添加主键约束
alter table userInfo
add constraint PK_uID primary key (uID)
--添加唯一约束
alter table userInfo
add constraint UQ_uIDNumber unique (uIDNummer)
--添加默认约束
alter table userInfo
add constraint DF_uGender default('女')  for uGender
--添加检查约束
alter table userInfo
add constraint CK_uAge check(uAge between 0 and 150 )
--添加外键约束
alter table passwordBook
add constraint FK_pUID foreign key(pUID) references userInfo(uID)
go
-----------------删除约束---------------
--alter table  表名
--drop constraint 约束名

-----------------创建登录账户-----------
--添加Window登陆账号--
exec sp_grantlogin 'windown 域名\域账户'
--添加SQL登陆账号--
exec sp_addlogin '用户名','密码'
go
-----------------创建数据库用户-----------
use MyNoteBook
go
exec sp_grantdbaccess '用户名','密码'
-----------------给数据库用户授权---------
--grant 权限 [on 表名] to 数据库用户 --权限:insert , delete , update , select , createtable

----------------获取当前登录的用户名----
select SYSTEM_USER

SELECT SUSER_NAME()

 


----------------T-SQL编程------------------------------
--1.变量---------------
-- 定义变量  declare @variable_name dataType
--局部变量赋值 set @variable_name value 或者 select @variable_name=value  
--全局变量
-- @@error    最后一个T-SQL错误的错误号
-- @@identity   最后一次插入的标识符
-- @@language   当前实用的语言的名称
-- @@max_connections 可以创建的同时连接的最大数目
-- @rowcount   受上一个SQL语句影响的行数
-- @@servername   本地服务器的名称
-- @@servicename  该计算机上的SQL服务的名称
-- @@timeticks      当前计算机上每刻度的微秒数
-- @@trancount      当前连接打开的事务数
-- @@version   SQL Server的版本信息

--2.输出语句---------------
print '服务器的名称:'+@@servername
select @@servername as '服务器名称'

--3.逻辑控制语句---------------
--if(条件)
--语句块
--else
--语句块

--begin end 相当于{}
   
--while(条件)
--语句块
--[break]

--case
-- when 条件1 then 结果1
-- when 条件2 then 结果2
-- when 条件3 then 结果3
--end

------------------------------------------
--in  not in
--exists not exists

-----------------------------事务(transaction) 、索引、视图----------------------------------------
-----------------------1.事务例子--------------------
--use stuDB
--go
--print '查看转账事务前的余额'
--select * from bank
--go
----开始事务
--begin transaction
--declare @errorSum int
--update bank set currentMoney=currenyMoney-1000 where customerName='张三'
--set @errorSum=@errorSum+@@error
--update bank set currentMoney=currenyMoney+1000 where customerName='李四'
--set @errorSum=@errorSum+@@error
--if @erroeSum>0
-- begin
--  rollback transaction --回滚事务
-- end
--else
-- begin
--  commit transaction --提交事务
-- end
--go

-----------------------2.索引-------------------
--if exists (select name from sysindexes where name='index_name')
--drop index 表名.index_name
--create [unique][clustered|nonclustered] index index_name
--on table_name(column_name[,column_name]..)
--[with
-- fillfactor=x
--]
--查询
--select * from 表名(index=index_name)where 条件

-------创建了唯一约束则自动创建唯一索引
-------主键索引,在数据据关系图中为表定义一个主键将自动创建主键索引,主键索引是唯一索引的特殊类型
-------聚集索引,在聚集索引中,表中各行的物理顺序与键值的逻辑(索引)相同。表只能包含一个聚集索引
--------在一个表中只能创建一个聚集索引,但可以有多个非聚集索引,设置某列为主键,该列就默认为聚集索引
--------unique(唯一索引)clustered(聚集索引)以及fillfactor填充因子(指定每个索引页的填满程度,一般很少指定)

 
-----------------------3.视图------------------------
--create view view_name
--as
-- 语句块
--go

----------------------4.存储过程---------------------
--create proc  存储过程名
--as

 

 

 

 

 

 

--------------------------------------T-SQL--------------------------------------
---1.新增数据--
--insert into 表名 (列名,列名,列名) values(值,值,值) default     --一次插入一条
--insert into 表名B(列名,列名,列名) select 列名,列名,列名 from 表名A   --通过insert select 语句将现有表中的数据添加到新表中
--select identity(int,1,1) A.列名,A.列名,A.列名 into 表名B from 表名A   --通过select into 语句将现有表中的数据添加到新表中
--insert 表名A(列名,列名,列名)                --通过union关键字合并数据进行插入
--select 值,值,值 union
--select 值,值,值 union
--select 值,值,值 union
--select 值,值,值 union
--select 值,值,值 union
--select 值,值,值

---2.更新数据--
--update 表名 set 列名=更新值 where 更新条件

---3.使用delete删除数据--
--delete from 表名 where 条件

---4.使用truncate Table删除数据
--truncate table 表名    --truncate table删除表中的所有行,但是表的结构、列、约束、索引等不会被改动,
         --truncate table 不能用于有外键约束引用的表,但是delete 可以
---5.查询数据--
--20%的数据  select top20 perecent 列名 from 表名 where 条件
--排序 order by asc(升序) desc(降序)


----------------------函数----------------------
---字符串函数---
--charindex  用来寻找一个指定的字符串在另一个字符串中的起始位置     select charindex('accp','my accp course',1)返回4   (从0开始)
--len     返回传递给他的字符串长度            select len('SQL Server课程') 返回12
--upper   把传递给它的字符串转换为大写           select upper('sql server课程')返回SQL SERVER课程
--ltrim   清除字符左边的空格             select ltrim(' accp ')返回accp (保留后面的空格)
--rtrim   清除字符右边的空格             select rtrim(' accp ')返回 accp(保留前面的空格)
--right   从字符串右边返回指定书数目的字符          select right('买买提.吐鲁番',3)返回 吐鲁番
--replace 替换一个字符串中的字符            select replace('默克可乐哈可可','可','兰')返回 默克兰乐哈兰兰
--stuff   在一个字符串中,删除指定长度的字符串,并在该位置插入一个新的字符串select stuff('ABCDEFG',2,3,'我的音乐我的世界') 返回A我的音乐我的世界EFG
 
---日期函数---
--getdate 取得当前的系统日期       select getDate() 返回今天的日期
--dateadd 将当前的数值添加到指定的日期部分后的日期 select dateadd(mm,4,'01/01/99')返回以当前的日期格式返回05/01/09
--datediff  两个日期之间的指定日期部分的区别   select datediff(mm,'01/01/09','05/01/99') 返回4
--datename 日期中指定日期部分的字符串形式    select datename(dw,'01/01/2000')返回星期六
--datepart 日期中指定日期部分的整数形式     select datepart(day,'01/15/2000')返回15

---数学函数---
--abs  取数值表达式的绝对值      select abs(-43) 返回43
--ceiling 取大于或等于指定数值、表达式的最小整数  select ceiling (43.5) 返回44
--floor  取小于或等于指定表达式的最大整数   select floor(43.5) 返回43
--power  取数值表达式的幂值        select power(5,2) 返回25
--round  将数值表达式四舍五入为指定精度    select round(43.543,1)返回43.500
--sign  对于正数返回+1,对于负数返回-1对于0返回0 select sign (-43) 返回-1
--sqrt  取浮点表达式的平方根      select sqrt(9) 返回3
 

---系统函数----
--convert  用来转变数据类型    select convert(varchar(5),12345)返回字符串12345
--current_user  返回当前用户的名字    select current_user 返回你当前登录的用户名
--datalength 返回用于指定表达式的字节数  select datalength ('中国A联盟')返回9
--host_name  返回当前用户所登陆的计算机名字  select host_name() 返回你所登录的计算机的名字
--system_user 返回当前所登录的用户名称  select system_user 返回你当前所登陆的用户名
--user_name  从给定的用户ID返回用户名  select user_name(1) 返回 从任意数据库中返回"dbo"
 

 

----------------模糊查询----------
---1.like---
---2.between---
---3.in---
 
----------------聚合函数----------
--sum--
--avg--
--max--
--min--
--count--

-----------having子句进行分组筛选----------


-------------多表联合查询的分类-------------
--left join 或 left outer join
--right join 或 left outer join
--full join 或 full outer join

--随机取出10条数据
--  select top 10 * from tablename order by newid()
--随机选择记录
--  select newid()
--删除重复记录
--  Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)
--列出数据库里所有的表名
--  select name from sysobjects where type='U'
--列出表里的所有的
--  select name from syscolumns where id=object_id('TableName')

posted @ 2012-03-27 00:15  不服输青年  阅读(314)  评论(0编辑  收藏  举报