• SQL批量删除与批量插入


    批量删除:

    DELETE FROM MyTable WHERE ID IN (1,2);

    批量插入:

    INSERT INTO MyTable(ID,NAME) VALUES(1,'123');
    INSERT INTO MyTable(ID,NAME) VALUES(2,'456');
    INSERT INTO MyTable(ID,NAME) VALUES(3,'789');

    第二种方法,使用UNION ALL来进行插入操作:    
    INSERT INTO MyTable(ID,NAME)
    SELECT 4,'000'
    UNION ALL
    SELECT 5,'001'
    UNION ALL
    SELECT 6,'002' ;
    据说要比第一种要快!

    第三种方法  
    INSERT INTO MyTable(ID,NAME) VALUES(7,'003'),(8,'004'),(9,'005');

    Example:

    表: leafjob(
    leafnum INT NOT NULL PRIMARY KEY,
    machine VARCHAR(15) );

    删除:delete from leafjob where leafnum in (1,2,4);

    插入:

    INSERT INTO leafjob (leafnum, machine) values(1, 'r1leaf3'), (2, 'r1leaf22');

    insert into leafjob(leafnum, machine) select 4,'000' union all select 1,'r1leaf3' union all select 2,'r1leaf22';

    insert into leafjob(leafnum, machine) select 1,'r1leaf3' union select 2,'r1leaf22';

    注:性能问题需要具体测试。示例在MySql下测试过,version: 4.1.20

    删除A表的a列等于1的数据

     代码如下 复制代码

    Delete from A where exists (Select 1 from A where a=1)

    上面的方法只适用于简单小数据量的批量数据删除了,如果是大批量数据删除我们可参考下面方法

     代码如下 复制代码

    Create PROCEDURE Batch_Delete 
    @TableName nvarchar(100), --表名 
    @FieldName nvarchar(100), --删除字段名 
    @DelCharIndexID nvarchar(1000) 
    as 
    DECLARE @PointerPrev int 
    DECLARE @PointerCurr int 
    DECLARE @TId NVARCHAR(50), @sql NVARCHAR(1000)

    Set @PointerPrev = 1 
    while (@PointerPrev < LEN(@DelCharIndexID)) 
    Begin 
    Set @PointerCurr = CharIndex(',',@DelCharIndexID,@PointerPrev) 
    if(@PointerCurr>0) 
    Begin 
    SET @TId = cast(SUBSTRING(@DelCharIndexID, @PointerPrev, @PointerCurr - @PointerPrev) As NVARCHAR(50)) 
    SET @sql = 'Delete From '+ @TableName +' Where '+ @FieldName + ' = '''+ @TID+'''' 
    Exec(@Sql) 
    Print('======='+@TId+'=======sql'+@Sql) 
    SET @PointerPrev = @PointerCurr + 1 
    Print(@PointerPrev) 
    End 
    else 
    Begin 
    Print('break') 
    Break 
    End 
    End 
    --删除最后一个,因为最后一个后面没有逗号,所以在循环中跳出,需另外再删除 
    SET @TId = cast(SUBSTRING(@DelCharIndexID, @PointerPrev, LEN(@DelCharIndexID) - @PointerPrev + 1) As NVARCHAR(50)) 
    SET @sql = 'Delete From '+ @TableName +' Where '+ @FieldName + ' = '''+ @TID+'''' 
    Exec(@Sql) 
    Print('======='+@TId+'=======sql'+@Sql) 
    GO

  • 相关阅读:
    反射创建对象
    DevExpress 日期输入框
    SsdlToSql10.tt文件内容
    ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
    DevExpress XtraCharts 图表导出PDF/XLS/JPEG
    Java中堆内存和栈内存详解(转)
    批量合并word文档
    java内部类总结(转)
    Java 之工厂方法和抽象工厂模式(转)
    Java GC 、引用
  • 原文地址:https://www.cnblogs.com/chengjun/p/4497198.html
Copyright © 2020-2023  润新知