[英]SQL Linked Server slow performance
我对数据库性能还是很陌生,并且了解Management Studio在后台为我们做的所有复杂工作,因此,对您的任何帮助或对学习资料的参考,我都感激不尽。
我的问题是我正在编写查询以从链接的服务器中获取数据,并将其加入到我的本地数据库表中以插入特定信息。 我正在使用2个CTE,并在CTE中加入2个表来链接服务器数据。 然后,我使用子查询将列添加到我的结果集中,以便可以逐行过滤情况。 我这样做是因为我不太擅长使用PIVOT。
with ap AS (
SELECT DISTINCT col1
,col2 ,col3 ,col4
from [linkedServer].[db].[dbo].[table] st
JOIN [linkedServer].[db].[dbo].[table2] vs ON vs.col1 = st.col1 AND vs.col2 = st.col2
WHERE vs.col3 = '' and ...
,pre as (
SELECT *
,COALESCE(
(SELECT 1 from ap where sss.col1 = ap.col1 and ap.col3 = '')
,(SELECT 2 from ap where sss.col1 = ap.col1 and ap.col3 = '')
,(SELECT 3 from ap where sss.col1 = ap.col1 and ap.col3 = '')
,(SELECT 4 from ap where sss.col1 = ap.col1 and ap.col3 = '')
) Monday
,COALESCE(
(SELECT 1 from ap where sss.col1 = ap.col1 and ap.col3 = '')
,(SELECT 2 from ap where sss.col1 = ap.col1 and ap.col3 = '')
,(SELECT 3 from ap where sss.col1 = ap.col1 and ap.col3 = '')
,(SELECT 4 from ap where sss.col1 = ap.col1 and ap.col3 = '')
) Tuesday
,COALESCE(
(SELECT 1 from ap where sss.col1 = ap.col1 and ap.col3 = '')
,(SELECT 2 from ap where sss.col1 = ap.col1 and ap.col3 = '')
,(SELECT 3 from ap where sss.col1 = ap.col1 and ap.col3 = '')
,(SELECT 4 from ap where sss.col1 = ap.col1 and ap.col3 = '')
) Wednesday
,COALESCE(
(SELECT 1 from ap where sss.col1 = ap.col1 and ap.col3 = '')
,(SELECT 2 from ap where sss.col1 = ap.col1 and ap.col3 = '')
,(SELECT 3 from ap where sss.col1 = ap.col1 and ap.col3 = '')
,(SELECT 4 from ap where sss.col1 = ap.col1 and ap.col3 = '')
) Thursday
FROM local_Table sss
)
UPDATE tar
SET tar.monday = pre.Monday
,tar.Tuesday = pre.Tuesday
,tar.Wednesday = pre.Wednesday
,tar.Thursday = pre.Thursday
FROM local_table tar
JOIN pre on tar.column = pre.column
运行大约需要5分钟。
根据到目前为止的经验,我的选择是使用临时表或在链接服务器上创建视图,因此我不会在查询中进行任何联接。
非常感谢您对此进行优化的帮助!
在链接服务器上使用此语法时:
select field1, field2
from servername.databasename.ownername.tablename
where field3 = something
发生的情况是,sql server将首先带入该表的全部内容,然后再应用where子句。 执行时间慢是由所有数据传输引起的。
解决方法是使用openquery。 如果您使用google,“ sql server openquery”,则会发现很多示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.