SqlServer性能优化 Sql语句优化(十四)
一:在较小的结果集上上操作
1.仅返回需要的列
2.分页获取数据
EF实现分页:
- public object getcp(int skiprows,int currentpagerows)
- {
- HRUser dbcontext = new HRUser();
- var cps = dbcontext.Product.Join(dbcontext.ProductCategory, a => a.ProductSubcategoryKey,
- ar => ar.ProductCategoryKey, (a, ar) => new
- {
- CName = ar.EnglishProductCategoryName,
- PName = a.EnglishProductName,
- Color = a.Color,
- Size = a.Size
- });
- return cps.OrderBy(p=>p.PName).Skip(skiprows).Take(currentpagerows).ToList();
- }
上一页:
- protected void Button4_Click(object sender, EventArgs e)
- {
- TextBox1.Text = (int.Parse(TextBox1.Text.Trim()) + 1).ToString();
- DataBinding();
- }
下一页:
- protected void Button4_Click(object sender, EventArgs e)
- {
- TextBox1.Text = (int.Parse(TextBox1.Text.Trim()) + 1).ToString();
- DataBinding();
- }
绑定:
- private void DataBinding()
- {
- var cps = p.getcp(int.Parse(TextBox1.Text.Trim())*10,10);
- GridView1.DataSource = cps;
- GridView1.DataBind();
- }
避免出现左侧计算:
- select * from EmployeeOp where VacationHours>=10*10
- select * from EmployeeOp where VacationHours/10>=10
建立合适的主外键:
- select c.EnglishProductCategoryName,p.EnglishProductName from Product as p
- inner join ProductCategory as c on c.ProductCategoryKey=p.ProductSubcategoryKey--0.214
- alter table ProductCategory
- add constraint pk_c_id primary key(ProductCategoryKey)
- alter table Product
- --不用去检查是否符合主外键的要求
- with nocheck
- add constraint fk_p_id foreign key(ProductSubcategoryKey) references ProductCategory(ProductCategoryKey)
- select c.EnglishProductCategoryName,p.EnglishProductName from Product as p
- inner join ProductCategory as c on c.ProductCategoryKey=p.ProductSubcategoryKey--性能好
验证数据存在时使用Exists替换Count():
- if ((select count(*) from EmployeeOp where VacationHours=100)>0)
- print 'hello'
- if exists(select * from EmployeeOp where VacationHours=100)
- print 'hello1'
关闭受影响的行数:
- set nocount on
- select * from Product
添加稀疏列:
- create table t1(c1 int identity(1,1),c2 int sparse)
- declare @count int
- set @count=0
- while @count<50000
- begin
- --定义稀疏列
- insert t1 values(null)
- set @count=@count+1
- end
- --查看表空间
- sp_spaceused 't1' --1408
- --删除稀疏列
- alter table t1
- alter column c2 drop sparse
- sp_spaceused 't1' --1712
- --添加稀疏列
- alter table t1
- alter column c2 add sparse
- sp_spaceused 't1' --1712
- dbcc shrinkdatabase('HRDB',1)
- --列集
- create table Student(id int,name varchar(500),sex varchar(500),sae int sparse,
- school varchar(500) sparse,optiondata xml column_set for all_sparse_columns)
- insert Student values (1,'caojian','man','<sae>35</sae><school>cdschool</school>')
- select *from Student
- select id,name,sex,sae,school,optiondata from Student
- update Student set optiondata ='<sae>36</sae>'
- update Student set school='sunliyuan'
- create table Sales(id int identity(1,1),amount int)
- alter table Sales
- add constraint ck_sales_amount check(amount>0)
- create table Sales1(id int identity(1,1),amount int)
- --创建规则 很多表都可以使用
- create rule amountrule as @amount>0
- --通过系统定义的方式 绑定
- exec sp_bindrule amountrule, 'Sales1.amount'
- --插入数据的时候就报错
- insert Sales1 values(0)
提高文件访问性能文件流:
打开SqlServer 配置管理工具:
找到如下的目录打开:
配置访问级别:
- --配置访问级别 数据库级别
- sp_configure 'filestream access level',2
- reconfigure
- select * from AdventureWorks2014.Production.Product
- select * from AdventureWorks2014.Production.ProductPhoto
- --链接表
- select * from AdventureWorks2014.Production.ProductProductPhoto
- --存在文件系统中
- --1.创建数据库
- drop database HRSales
- create database HRSales
- on primary
- (
- name='HRSales_data',
- filename='f:\HRSales_Data.mdf'
- ),
- --做文件组 --包含filestream
- filegroup filestreamfilegroup contains filestream
- (
- name='HRSaels_Blob',
- filename='f:\HRSalesblob'
- )
- use HRSales
- go
- create table Product(ID uniqueidentifier RowGUIDCol unique not null,
- name varchar(500),
- image varbinary(max) filestream
- )
- --插入记录
- insert into Product select NEWID(),p.Name,pp.LargePhoto from
- AdventureWorks2014.Production.Product as p inner join
- AdventureWorks2014.Production.ProductProductPhoto as ppp on p.ProductID=ppp.ProductID inner join
- AdventureWorks2014.Production.ProductPhoto as pp on ppp.ProductPhotoID=pp.ProductPhotoID
- select * from Product
查看IO:
- set statistics io on
- select * from AdventureWorks2014.Production.ProductPhoto--io 52
- set statistics io off
- set statistics io on
- select * from Product--7
- set statistics io off
创建数据库备份设备:
- --创建备份设备
- sp_addumpdevice 'disk','hrsalesbak','d:\hrsalesbak.bak'
- --备份
- backup database HRSales to hrsalesbak with name='HRSales Full',format
- --恢复
- restore database HRSales from hrsalesbak with file=1,recovery
文件进行了恢复:
在.Net中的显示:
- <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
- <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="显示" />
- <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
- <Columns>
- <asp:BoundField DataField="ID" HeaderText="ID" Visible="False" />
- <asp:BoundField DataField="name" HeaderText="产品名" />
- <asp:TemplateField HeaderText="样图">
- <ItemTemplate>
- <asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ID="+Eval("ID") %>' />
- </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- </asp:GridView>
- </asp:Content>
Model层:
- SalesDbcontext dbcontext = new SalesDbcontext();
- public object GetAllProduct()
- {
- var allproducts = dbcontext.Product;
- return allproducts.ToList();
- }
- public byte[] GetImageByProductID(Guid id)
- {
- var product = dbcontext.Product.Where(p => p.ID == id).FirstOrDefault();
- return product.image;
- }
后台的调用代码:
- /// <summary>
- /// ImageHandler 的摘要说明
- /// </summary>
- public class ImageHandler : IHttpHandler
- {
- Product p = new Product();
- MemoryStream memorystream = new MemoryStream();
- public void ProcessRequest(HttpContext context)
- {
- var id = Guid.Parse(context.Request.QueryString["ID"]);
- var image = p.GetImageByProductID(id);
- memorystream.Write(image, 0, image.Length);
- context.Response.Buffer = true;
- context.Response.BinaryWrite(image);
- memorystream.Dispose();
- }
- public bool IsReusable
- {
- get
- {
- return false;
- }
- }
- }
SqlServer性能优化 Sql语句优化(十四)的更多相关文章
- 看懂SqlServer查询计划 SQL语句优化分析
转自 http://www.cnblogs.com/fish-li/archive/2011/06/06/2073626.html 阅读目录 开始 SQL Server 查找记录的方法 SQL Ser ...
- 三,mysql优化--sql语句优化之索引一
1,需求:如何在一个项目中,找到慢查询的select,mysql数据库支持把慢查询语句,记录到日志中.供程序员分析.(默认不启用此功能,需要手动启用) 修改my.cnf文件(有些地方是my.ini) ...
- 四,mysql优化——sql语句优化之索引二
1,在什么列适合添加索引 (1)较频繁的作为查询条件字段应该添加索引 select * from emp where empid = 2; (2)唯一性太差的字段不适合添加索引,即时频繁作为查询条件. ...
- 五,mysql优化——sql语句优化小技巧
1,大批量插入数据 (1)对于MyISAM: alter table table_name disable keys; loading data; alter table table_name ena ...
- SQL语句(十四)子查询
--1. 使用IN关键字 --例1 查询系别人数不足5人的系别中学生的学号.姓名和系别 --系别人数不足5人的系别 ==>选择条件 select Sdept from Student Group ...
- 数据库 基于索引的SQL语句优化之降龙十八掌(转)
一篇挺不错的关于SQL语句优化的文章,因不知原始出处,故未作引用说明! 1 前言 客服业务受到SQL语句的影响非常大,在规模比较大的局点,往往因为一个小的SQL语句不够优化,导致数据库性能急 ...
- 转:sql语句优化
性能不理想的系统中除了一部分是因为应用程序的负载确实超过了服务器的实际处理能力外,更多的是因为系统存在大量的SQL语句需要优化. 为了获得稳定的执行性能,SQL语句越简单越好.对复杂的SQL语句,要设 ...
- 关于索引的sql语句优化之降龙十八掌
1 前言 客服业务受到SQL语句的影响非常大,在规模比较大的局点,往往因为一个小的SQL语句不够优化,导致数据库性能急剧下降,小型机idle所剩无几,应用服务器断连.超时,严重影响业务的正 ...
- sql语句优化 (转)
性能不理想的系统中除了一部分是因为应用程序的负载确实超过了服务器的实际处理能力外,更多的是因为系统存在大量的SQL语句需要优化. 为了获得稳定的执行性能,SQL语句越简单越好.对复杂的SQL语句,要设 ...
随机推荐
- Tomcat权威指南-读书摘要系列3
3. 在Tomcat中部署Servlet与JSP Web应用程序 jar命令打包war文件 jar cvf examples.war .
- MySQL数据库应用 从入门到精通 学习笔记
以下内容是学习<MySQL数据库应用 从入门到精通>过程中总结的一些内容提要,供以后自己复现使用. 一:数据库查看所有数据库: SHOW DATABASES创建数据库: CREATE DA ...
- PHP7 学习笔记(二)PHP5.9 升级到PHP7 遇到的一些坑的记录(php-fpm 图解)
apache_event_php-fpm 示意图: nginx-php-fpm示意图: Worker-Master-Server TCP-Nginx_PHP Nginx-FastCGI 1.使用$_G ...
- Web API: Client: Call a Web API from a .net client
原文地址: http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client 翻译地址:h ...
- vbs 解析 html 文档
关于VBS采集,网上流行比较多的方法都是正则,其实 htmlfile 可以解析 html 代码,但如果 designMode 没开启的话,有时候会包安全提示信息.但是开启 designMode (@预 ...
- IE10下 FormsAuthentication.SetAuthCookie无效的问
问题是这样的,我在本地测试设置身份验证票据都没问题,发布到服务器后访问地址添加了一些特殊的字符,看起来像加过密的,如下: http://www.example.com/(F(1xe9eXIxPzMAL ...
- 洛谷P3953 [NOIP2017]逛公园
K<=50,感觉可以DP 先建反图求出从n到各个点的最短路,然后在正图上DP 设f[当前点][比最短路多走的距离]=方案数 转移显然是 $f[v][res]=\sum f[u][res+tmp] ...
- Tetrahedron(Codeforces Round #113 (Div. 2) + 打表找规律 + dp计数)
题目链接: https://codeforces.com/contest/166/problem/E 题目: 题意: 给你一个三菱锥,初始时你在D点,然后你每次可以往相邻的顶点移动,问你第n步回到D点 ...
- NodeJS让前端与后端更友好的分手
学问 最近“上层建筑”在兴起国学热,所以公司几个月前决定开发一款名叫“学问”的有关于国学的app. APP的详情页面还是由web来显现具体内容,有些类似于新闻页,图文混排什么的web是最适 ...
- 常见踩坑案例(二)-Request method 'POST' not supported
一 前言 最近涉及到与前后端的数据对接,按道理来说没一点压力结果被一前端童鞋带坑里去了(不过也是很久没写过这种前后端分离进行联调的事情了,如果是一个人全套弄的话就不会出现下面问题). 二 Reques ...