1

私はまだデータベースのパフォーマンスにまったく慣れておらず、管理スタジオが舞台裏で私たちのために行っているすべての複雑さを理解しているので、学習資料への助けや参照は大歓迎です.

私の問題は、リンク サーバーからデータを取得し、それをローカルの 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 分かかります。

これまでに学んだことから、私のオプションは、一時テーブルを使用するか、リンク サーバー上にビューを作成することです。そのため、クエリで結合を行っていません。

これを最適化するための助けがあれば大歓迎です!

4

1 に答える 1

0

リンク サーバーでこの構文を使用すると、次のようになります。

select field1, field2
from servername.databasename.ownername.tablename
where field3 = something

何が起こるかというと、SQL サーバーは最初にそのテーブルの内容全体を取り込み、後で where 句を適用します。実行時間が遅いのは、転送されるすべてのデータが原因です。

回避策は、openquery を使用することです。「sql server openquery」とググると、たくさんの例が見つかります。

于 2013-10-28T22:45:32.493 に答える