• 分割以逗号作为分割符号的字符串并插入到表中


    SQL语句如下:
    DECLARE @temp varchar(50)
    DECLARE @post int
    DECLARE @endpost int
    DECLARE @flag bit
    SET @flag = 1
    SET @post = 0
    SET @temp='1,2,3,4,'

    WHILE(@flag = 1)
    BEGIN
    SET @endpost = charindex(',',@temp)
    IF(@endpost > 0)
    BEGIN
    INSERT INTO [str] (chr) VALUES (substring(@temp,1,@endpost-1))
    SET @temp = right(@temp,len(@temp)-@endpost)
    END
    ELSE
    BEGIN
    IF(@temp <> '')
    BEGIN
    INSERT INTO [str] (chr) VALUES (@temp)
    SET @flag = 0
    END
    ELSE
    SET @flag = 0
    END
    END

    我使用的是下面这个版本

    BEGIN  
      declare spot SMALLINT;
      declare TId int;
      WHILE (CampaignId_Array <> '') DO  
      SET spot=instr(CampaignId_Array,',');
      IF spot > 0
      THEN  
      SET TId = Cast(LEFT(CampaignId_Array, spot-1) as SIGNED);
      SET CampaignId_Array = RIGHT(CampaignId_Array, LENGTH(CampaignId_Array)-spot);  
      ELSE  
      SET TId = Cast(CampaignId_Array as SIGNED);
      SET CampaignId_Array = '';  
    END IF; 
    Insert into campaign_asset (campaign_id, asset_id, advertiser_id,created_by) 
      values (TId, Asset_id, Advertiser_id, Created_by);
      END WHILE;
    END

    实际使用

    DECLARE spot SMALLINT;  -- 分隔符的位置
    DECLARE tempCid VARCHAR(64);  -- 循环插入到表tb_sc_tmrecive需要用到的临时的Cid

    -- 这里要对 ClassId_Array 进行循环了,进行,分隔循环insert到表`tb_sc_tmrecive`来
            WHILE (ClassId_Array <> '') DO  
              SET spot=INSTR(ClassId_Array,',');
              IF spot > 0
              THEN  
              SET tempCid = LEFT(ClassId_Array, spot-1) ;
              SET ClassId_Array = RIGHT(ClassId_Array, LENGTH(ClassId_Array)-spot);  
              ELSE  
              SET tempCid = ClassId_Array ;
              SET ClassId_Array = '';  
            END IF; 
            INSERT INTO `tb_sc_tmrecive`(`MId`,`CId`) VALUES (intId,tempCid); -- 循环了每个班级id,插入到表 tb_sc_TMRecive
            END WHILE;
        -- 分隔插入结束

    image

  • 相关阅读:
    Thinkphp5.0 模型hasOne、hasMany、belongsTo详解
    ES6中async和await说明和用法
    必会SQL练习题
    Git初识学习
    CI框架简单使用
    JavaScript 的 this 原理
    javascript实现游戏贪吃蛇
    js清除childNodes中的#text(选项卡中会用到获取第一级子元素)
    JavaNIO
    MongoDB入门_shell基本操作
  • 原文地址:https://www.cnblogs.com/joeylee/p/2919208.html
Copyright © 2020-2023  润新知