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语句,要设 ...
随机推荐
- Git2:Git基本操作
目录 一.git全局配置 二.创建一个版本库 三.git的常用操作 1.版本提交与回退 1.1.版本提交 1.2.版本回退 2.工作区.版本库与暂存区 2.1.工作区 2.2.版本库 3.管理文件的修 ...
- Java基础-线程操作共享数据的安全问题
Java基础-线程操作共享数据的安全问题 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.引发线程安全问题 如果有多个线程在同时运行,而这些线程可能会同时运行这段代码.程序每次运 ...
- List保存在ViewState
private List<SYSUAO> UserRoleList { get { return ViewState["UserRoleList"] as List&l ...
- RabbitMQ基础介绍
非原创,仅作为个人的学习资料,转自 anzhsoft http://blog.csdn.net/anzhsoft/article/details/19563091, 1. 历史 RabbitMQ是一个 ...
- MacBook Air网络问题
自从买了本本之后,一直觉得无线网连接不能正常使用,最开始觉得是网络不给力,因为图标都没有满格.后来搬家,网速家里的window,iphone设备都能正常使用,就我的mac 本本图标显示满格,但是网页打 ...
- python json 访问与字符串截取
# req = requests.Request(url=url, headers=headers, data=data) # html = requests.get(req) # print(htm ...
- asp.net WebForm程序删除.designer.cs文件之后的故事
1.介绍 正常情况下添加一个WebForm程序结构如下(命名为:myWebForm.aspx) 文件说明:.aspx文件:书写html代码部分,以及javascript,css等代码书写及引用 .as ...
- 【leetcode 简单】 第一百零七题 回旋镖的数量
给定平面上 n 对不同的点,“回旋镖” 是由点表示的元组 (i, j, k) ,其中 i 和 j 之间的距离和 i 和 k 之间的距离相等(需要考虑元组的顺序). 找到所有回旋镖的数量.你可以假设 n ...
- 差分约束系统+spfa(B - World Exhibition HDU - 3592 )
题目链接:https://cn.vjudge.net/contest/276233#problem/B 思路和上一个一样,不过注意点有两个,第一,对dis数组进行初始化的时候,应该初始化成ox3f3f ...
- iOS学习笔记(4)— UITableView的重用机制
UITableView中的cell是动态的,在使用过程中,系统会根据屏幕的高度(480)和每个cell的高度计算屏幕中需要显示的cell的个数.比如,cell高度为90.那么480 / 90 = 5 ...