J'utilise l'instruction MERGE
pour augmenter les lignes d'une base de données SQL Server 2008. Cependant, mon sproc est une opération à une seule rangée, alors qu'en fait je préfère les traiter par lot. Est-ce possible et, si oui, comment le faire?Comment est-ce que je fais des upserts par lots dans SQL Server?
3
A
Répondre
5
Pouvez-vous utiliser les paramètres de table dans votre proc? Jetez un coup d'oeil ici http://www.sommarskog.se/arrays-in-sql-2008.html#TVP_in_TSQL pour obtenir quelques idées
Ensuite, dans le proc vous pouvez utiliser Merge contre le PVT
3
j'ai créé un proc appelé « upsert » qui prend un nom de table cible, nom de la table source, champs join sur, et les champs à mettre à jour (les champs sont séparés par des virgules), puis effectue la fusion de manière dynamique.
le code est ci-dessous.
CREATE proc [common].[upsert](@source nvarchar(100), @target nvarchar(100), @join_field nvarchar(100), @fields nvarchar(200))
as
[email protected] is the table name that holds the rows that you want to either update or insert into @target table
[email protected]_field is the 1 field on which the two tables will be joined...you can only join on 1 field right now!
[email protected] are the comma separated fields that will either be updated or inserted into @target. They must be the same name in @source and @target
declare @sql nvarchar(max)
set @sql = '
merge '+ @target +' as target
using '+ @source +' as source
on target.'+ @join_field +' = source.'+ @join_field +'
when matched then
update set
' + common.upsert_update_fields_string_builder('source', 'target', @fields) + '
when not matched then
insert ('+ @join_field +', '+ @fields +')
values (source.'+ @join_field +',' + common.upsert_insert_fields_string_builder('source', @fields) +');
'
exec(@sql)
CREATE function [common].[upsert_insert_fields_string_builder](@source nvarchar(100), @fields nvarchar(200))
returns nvarchar(1000)
as
begin
declare @string nvarchar(max)
select @string = coalesce(
@string + ',' + @source + '.' + items,
@source +'.' + items)
from common.split_string(@fields,',')
return @string
end
CREATE function [common].[upsert_update_fields_string_builder](@source nvarchar(100), @target nvarchar(100), @fields nvarchar(200))
returns nvarchar(1000)
as
begin
declare @string nvarchar(max)
select @string = coalesce(
@string + ', '+ @target + '.' + items + '=' + @source + '.' + items,
''+ @target +'.' + items + '='+ @source +'.' + items)
from common.split_string(@fields,',')
return @string
end
Oui, ce serait bien de jeter un oeil. S'il vous plaît poster un lien si vous le pouvez - merci. –
vient d'éditer la réponse pour inclure le code. J'espère que ça marche pour toi! Je l'ai trouvé utile à plusieurs reprises. – thomas