【问题标题】:Insert a fixed number of rows 2000 at a time in sql server在sql server中一次插入固定数量的行2000
【发布时间】:2008-09-25 14:23:30
【问题描述】:

我想一次将 50,000 条记录插入 sql server 数据库 2000。如何做到这一点?

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    您可以使用 SELECT TOP 子句:在 MSSQL 2005 中,它进行了扩展,允许您使用变量来指定记录数(旧版本只允许使用数字常量)

    你可以试试这样: (未经测试,因为我目前无法访问 MSSQL2005)

    begin
    declare @n int, @rows int
    
        select @rows = count(*) from sourcetable
    
        select @n=0
    
        while @n < @rows
        begin
    
            insert into desttable
            select top 2000 * 
            from sourcetable
            where id_sourcetable not in (select top (@n) id_sourcetable 
                        from sourcetable 
                        order by id_sourcetable)
            order by id_sourcetable
    
            select @n=@n+2000
        end
    end
    

    【讨论】:

    • 是的,我做了类似的事情。但是我没有使用 NOT IN,而是使用了 NOT EXISTS,这应该可以提供更好的性能。
    【解决方案2】:

    您是从另一个数据库/表插入,以编程方式还是从平面文件插入?

    【讨论】:

      【解决方案3】:

      来自外部数据源bcp 可用于导入数据。 -b 开关允许您指定批量大小。

      【讨论】:

        【解决方案4】:

        您的意思是进行某种测试吗?

        declare @index integer
        set @index = 0
        while @index < 50000
        begin
           insert into table
           values (x,y,z)
           set @index = @index + 1
        end
        

        但我想这不是你的意思。

        如果您指的是进行批量插入的最佳方式,请使用 BULK INSERTbcp 之类的东西

        【讨论】:

        • 不完全是。 50,000 行,但每次 2000 行。
        【解决方案5】:

        将@rows 声明为 int 设置@rows = 1 而@rows >0

        开始

        insert mytable (field1, field2, field3)
        select   top 2000 pa.field1, pa.field2, pa.field3 
        from table1 pa (nolock) 
        left join mytable ta (nolock)on ta.field2 = pa.feild2
            and ta.field3 = pa.field3 and ta.field1 = pa.field1
        where ta.field1 is null
        order by pa.field1
        

        设置@rows = @@rowcount

        结束

        这是我们目前在 SQL Server 2000 生产环境中使用的代码,其中表名和字段名已更改。

        【讨论】:

          【解决方案6】:

          使用 SQL 2000,我可能会依靠 DTS 来执行此操作,具体取决于数据所在的位置。您可以明确告诉 DTS 将什么用于批量提交大小。否则,SQL 2005 批处理解决方案的修改版本会很好。我认为您不能在 SQL 2000 中将 TOP 与变量一起使用。

          【讨论】:

          • 我确认,变量的使用是用SQL2005添加的
          猜你喜欢
          • 2010-10-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-15
          • 2017-12-02
          • 2013-01-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多