私はまだデータベースのパフォーマンスにまったく慣れておらず、管理スタジオが舞台裏で私たちのために行っているすべての複雑さを理解しているので、学習資料への助けや参照は大歓迎です.
私の問題は、リンク サーバーからデータを取得し、それをローカルの db テーブルに結合して特定の情報を挿入するためのクエリを作成していることです。リンクサーバーデータ用に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 分かかります。
これまでに学んだことから、私のオプションは、一時テーブルを使用するか、リンク サーバー上にビューを作成することです。そのため、クエリで結合を行っていません。
これを最適化するための助けがあれば大歓迎です!