我有一个包含用户定义字段的表,我希望根据另一个表保持更新。为了做到这一点,我创建了以下查询
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 :(得分: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
答案 1 :(得分: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