SQL Server个人笔记

遇到问题了就来记录一下,暂时不会深入研究数据库

查看语句执行效率

执行计划查看

可以直接使用显示预估的执行计划查看,选中语句,直接选择执行计划即可

语句查看

set statistics profile on 
set statistics io on 
set statistics time on 
go 

--两个go中间为你执行的sql语句
select * from Product p where exists (select id from JotrinDB.dbo.MarkingCode where PartNumber=p.ProductName and MarkingCode like '100%')

go 
set statistics profile off 
set statistics io off 
set statistics time off

最好不要使用in,*

这是我写的SQL,有两个不好的地方

select * from Product where productName in (select PartNumber from JotrinDB.dbo.MarkingCode where MarkingCode like '100%')
  1. 在程序中,切记不能使用*
  2. 最好不要使用in,改成exists,而且最好exists的字段是id这类有索引的

改完之后的sql语句如下,要什么数据写什么,使用exists判断id

select p.Name,p.Data from Product p where exists (select id from JotrinDB.dbo.MarkingCode where PartNumber=p.ProductName and MarkingCode like '100%')

多条重复数据只查一个:row_number() over() 函数

先来查看我的数据表,内容是这样的

Id Name Age Date
1 许嵩 33 2020-03-24
2 许嵩 33 2020-03-24
3 许嵩 33 2020-03-24
4 许嵩 33 2020-03-25
5 许嵩 33 2020-03-24
6 许嵩 33 2020-03-24
7 蜀云泉 25 2020-03-24
8 蜀云泉 25 2020-03-24
9 蜀云泉 25 2020-03-24
10 蜀云泉 25 2020-03-25
11 蜀云泉 25 2020-03-24
12 蜀云泉 25 2020-03-24
13 许嵩 32 2019-03-24
14 许嵩 32 2019-03-24
15 许嵩 32 2019-03-24
16 许嵩 32 2019-03-25
17 许嵩 32 2019-03-24
18 许嵩 32 2019-03-24
19 蜀云泉 24 2019-03-24
20 蜀云泉 24 2019-03-24
21 蜀云泉 24 2019-03-25
22 蜀云泉 24 2019-03-24
23 蜀云泉 24 2019-03-24
24 许嵩 33 2020-03-25
25 许嵩 32 2019-03-25
26 蜀云泉 25 2020-03-25
27 蜀云泉 24 2019-03-25

我现在的需求是这样的,我输入一个姓名,给我查出来这个人的记录,要求每个年龄只要最新的日期,不要重复的数据

如果按照我之前的水平,我会这样写

select * from VaeDB.dbo.test  where Id in (
	select min(t.Id) Id from (
		select * from VaeDB.dbo.test where Date in (
			select MAX(Date) Date  from VaeDB.dbo.test group by Name,Age
		)
	) t group by t.Name,t.Age having COUNT(1) > 1
)

很麻烦,真的很麻烦,因为group by使用之后,前面的select查询不能查Id了,必须使用聚合函数Max,Min之类的,但是我的Id最大的最小的都可能不是日期最新的,所以,很麻烦

新方法就是使用row_number() over() 函数,这个太好用了,sql如下

select t.* from(
	select VaeDB.dbo.test .*,row_number() over (partition by age order by Date desc) rn from VaeDB.dbo.test 
) t where rn=1;

查看表的所有列名

select name from syscolumns Where id=object_Id('Table_Name');

查找内容有没有中文

select * from Family where Name like '%[吖-座]%' 

对没错,[吖-座]就包括了所有的中文 🐷

查找特殊字符

我在查找・这个符号的时候,使用like,没有用,查不出来,加个N就可以了

select * from test where name like N'%・%'

GUID

select LOWER(REPLACE(NEWID(),'-',''))
posted @ 2019-09-27 16:39  蜀云泉  阅读(266)  评论(0编辑  收藏  举报