MS SqlServer中少用但是好用的SQL语句

代码
/*
-- 2010-02-26 
-- 布朗
-- QQ:156298979
*/ 

-- with ties可以附加与排序字段相同值的多个行
select  top 3  with ties * from hrEmployee order by shortName asc

set rowcount 3 --设置全局变量,使每次返回的行数都为3行
select * from hrEmployee order by shortName asc

set rowcount 0 --设置全局变量,使每次返回的行数为所有行


-- select ...where 符合代替if语句
declare @m int ,@n int ,@i int
set @m=4 
set @n=1
select @i= ceiling(@m/@nwhere @m>@n
select @i

--服务器环境信息
select  serverproperty('Edition')

--字符串函数 
--
将一个字符串指定位置开始指定长度的内容替换成新串的值
select stuff('abcedefg',3,2,'1234')

--搜索子串在父串的位置
select CharIndex('c','abcdefg',1)
select PatIndex('%[cd]%','abcdefg')

--发音相似的词或名称
select soundex('lfc')
--返回两个字符串的差异程度
select Difference('abcd','abce')


inner join --内连接
left outer join --左外连接
right outer join --右外连接
full outer join --全外连接
cross outer join --交叉连接 A表4条记录,B表5条记录,交叉后生成20条记录(笛卡尔乘积)


--两个表合并
select * from hrEmployeeA 
union all 
select * from hrEmployeeB

--两个表相交
select distinct(UserName) 
from 
(
select distinct(UserName) from hrEmployeeA 
union all 
select distinct(UserName) from hrEmployeeB
) Emp
group by UserName

--两个表关系除
--
两个表关系差(集合差)

 

--全文索引 
exec sp_fulltext_database 'enable' --启用全文检索 'disable'禁用
create fulltext catalog nofc2 as default--为数据库创建全文目录
create fulltext index on hrEmployee([Name],[ShortName],[Description]--创建针对数据库中某个表的一列或多列的全文索引。每个表只允许有一个全文索引
 Key Index PK_hrEmployee
--全文检索
select * from hrEmployee where Contains(hrEmployee.*,''and Contains(hrEmployee.*,''--(where Contains类似 where in())
--
全文检索
select * from ContainsTable (hrEmployee,*,'')
--临近的词,屈折变体,

--全文检索-模糊查询
select * from hrEmployee where FreeText(*,'')
select * from FreeTextTable(hrEmployee,*,'')

drop fulltext index on hrEmployee
drop fulltext catalog nofc2
exec sp_fulltext_database 'disable'


--视图加密
create view Vabc as
(
select * from hrEmployee
)
with Encryption
--WITH CHECK OPTION / SCHEMABINDING / VIEW_METADATA


--Insert语句
--
Insert/values
--
Insert/select
--
Insert/exec   --插入存储过程的结果集
insert into hrEmployee (Name,shortName,Description) exec sp_hrGetEmployee 
--insert Default --插入表的默认值
insert into hrEmployee default values


--Update语句连接多个表
update hrEmployee 
set Salary = Salary * (1 + 2* case when t1.EnterTime > '2000-01-01' then 1 else 0 end )  from hrEmployee t1 join zj_Dept t2 on t1.DeptID = t2.DeptID


--Delete语句 连接多个表
delete from zj_Operation_Log
from zj_Operation_Log t1 
join zj_Dept t2 on t1.DeptNo = t2.DeptNo
where t2.DeptName='行政部'

 

--标识值
select @@identity   --全局变量所有表最所生成的最近一个标识值
select Scope_identity()  --批处理或者最近的作用域中所生成的最近一个标识值
select ident_current('hrEmployee'--指定表名的表所生成的最近一个标识值

--全局唯一标识符
select newid()
原文地址:https://www.cnblogs.com/hantianwei/p/1674476.html