代码之家  ›  专栏  ›  技术社区  ›  Dmitri Nesteruk

如何在SQL Server中执行批处理升迁?

  •  3
  • Dmitri Nesteruk  · 技术社区  · 15 年前

    我用的是 MERGE 语句在SQLServer2008数据库中向上插入行。然而,我的存储过程是一个单行操作,而实际上我更喜欢批处理这些操作。这有可能吗?如果有,我该怎么做?

    2 回复  |  直到 15 年前
        1
  •  5
  •   SQLMenace    15 年前

    你能在过程中使用表值参数吗?看看这里 http://www.sommarskog.se/arrays-in-sql-2008.html#TVP_in_TSQL

    然后在过程中,你可以使用合并对TVP

        2
  •  3
  •   thomas    15 年前

    代码如下。

        CREATE proc [common].[upsert](@source nvarchar(100), @target nvarchar(100), @join_field nvarchar(100), @fields nvarchar(200))
        as
    
        --@source is the table name that holds the rows that you want to either update or insert into @target table
        --@join_field is the 1 field on which the two tables will be joined...you can only join on 1 field right now!
        --@fields 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