2017-11-30 28 views
1

enter image description hereTSQL更新ステートメント実行

私はユーザー定義フィールドのテーブルを持っています。私は別のテーブルに基づいて更新したがっています。私は次のクエリを作成しました。

select 
    a + b + c + d + e + f + g + h 
from 
    (select 
     'update gl00100 set USERDEF1 =' as a, 
     '''' + DMA + '''' as b, 
     ', set USERDEF2 =' as c, 
     '''' + Brand + '''' as d, 
     ', set USRDEFS1 =' as e, 
     '''' + convert(char(10), dateopened, 120) + '''' as f, 
     'where actnumbr_2 =' as g, 
     GPStore as h 
    from 
     [192.168.xxx.xx].bi.dbo.store 
    where 
     store <> 0000 and DateOpened is not null) x 

私は実行したい更新文を作成していると分かります。どのようにクエリを実行し、結果を実行することができます。それも可能ですか?

+0

あなたは動的なSQLを使用する必要があります –

答えて

1

ことは、これを試してみてください:

DECLARE @sql nvarchar(2000) 
DECLARE #crs INSENSITIVE CURSOR FOR 
SELECT 'update gl00100 set USERDEF1 =' as a, ''''+DMA+'''' as b, ', 
    set USERDEF2 =' as c, ''''+Brand+'''' as d, ', set USRDEFS1 =' as e, 
    ''''+convert(char(10),dateopened,120)+'''' as f, 'where actnumbr_2 =' as g, 
    GPStore as h 
from [192.168.xxx.xx].bi.dbo.store where store <> 0000 and DateOpened is not null 
OPEN #crs 
FETCH NEXT FROM #crs INTO @sql 
WHILE @@FETCH_STATUS = 0 
BEGIN 
    EXEC sp_executesql @sql 
    FETCH NEXT FROM #crs INTO @sql 
END 
CLOSE #crs 
DEALLOCATE #crs 
+0

これは魅力的に働いた!ありがとうございました –

+0

@ShelanPatel:あなたは初心者ですから。私の答えがあなたの目標を達成するなら、それを受け入れてください –

0

あなたはJOINではなく、動的SQL文を構築し、それらを一つずつ実行を使用してこれを行うことができます。

UPDATE g 
SET  USERDEF1 = s.DMA, 
     USERDEF2 = s.Brand, 
     USRDEFS1 = s.DateOpened 
FROM gl00100 AS g 
     INNER JOIN [192.168.xxx.xx].bi.dbo.store AS s 
      ON s.GPStore = g.actnumbr_2 
WHERE s.Store <> 0000 
AND  s.DateOpened IS NOT NULL; 

あなたが使用して、より良いパフォーマンスを得るにも見つけることができOPENQUERYでは、クロスサーバクエリに4つの部分名を使用すると統計情報も利用できないため、最後に数行を選択するだけでストアテーブル全体をメモリにプルアップする可能性があります。だからこのようなものを試してみてください:

UPDATE g 
SET  USERDEF1 = s.DMA, 
     USERDEF2 = s.Brand, 
     USRDEFS1 = s.DateOpened 
FROM gl00100 AS g 
     INNER JOIN OPENQUERY 
     ( [192.168.xxx.xx], 
      'SELECT DMA, Brand, DateOpened, GPStore 
      FROM bi.dbo.store 
      WHERE store <> 0000 AND DateOpened is not null' 
     ) AS s 
      ON s.GPStore = g.actnumbr_2 
関連する問題