在 sql 服务器中插入时将一行拆分为两行

split one row to two rows while inserting in sql server

我有一个原始 table,我想根据类别将一行拆分为两行。 我的代码现在按预期工作。但我想删除 while 循环来完成这个任务。

我无法使用批量插入来完成此操作我的代码不适用于更多记录,因为我正在 excel 上传时执行此操作。

CREATE TABLE #RAW_TABLE (ID INT IDENTITY(1,1),FIELD1 VARCHAR(100),CATEGORY VARCHAR(100))

INSERT INTO #RAW_TABLE (FIELD1,CATEGORY) VALUES ('DATA','SINGLE')
INSERT INTO #RAW_TABLE (FIELD1,CATEGORY) VALUES ('DATA','SINGLE')
INSERT INTO #RAW_TABLE (FIELD1,CATEGORY) VALUES ('DATA','SPLIT')
INSERT INTO #RAW_TABLE (FIELD1,CATEGORY) VALUES ('DATA','SINGLE')
INSERT INTO #RAW_TABLE (FIELD1,CATEGORY) VALUES ('DATA','SINGLE')

CREATE TABLE #PROCESSED_TABLE (ID INT IDENTITY(1,1),FIELD1 VARCHAR(100),CATEGORY VARCHAR(100))

Declare @Int int,@Field1 Varchar(100),@Category Varchar(100)
WHILE ((SELECT COUNT(*) FROM #RAW_TABLE) > 0)
BEGIN   
    PRINT ''
    SELECT top 1 @Int = ID,@Field1 = FIELD1,@Category = CATEGORY FROM #RAW_TABLE 

    if(@Category = 'SPLIT')
    begin   
        insert into #PROCESSED_TABLE (FIELD1,CATEGORY) values (@Field1 + '-1',@Category)
        insert into #PROCESSED_TABLE (FIELD1,CATEGORY) values (@Field1 + '-2',@Category)
    end
    else
    begin
        insert into #PROCESSED_TABLE (FIELD1,CATEGORY) Values (@Field1,@Category)
    end

    Delete from #RAW_TABLE Where id = @Int 
END


Select * From #PROCESSED_TABLE 

输出:-

你可以用一个查询来做你想做的事。无需循环:

insert into #processed_table (field1, category)
    select (case when rt.category = 'SPLIT'
                 then concat(rt.field1, '-', v.n)
                 else rt.field1
            end), rt.category
    from #raw_table rt cross join
         (values (1), (2)) v(n)
    where v.n = 1 or rt.category = 'SPLIT';

您可以为 SPLIT 记录放置 UNION ALL 和 INSERT 两次。

insert into #PROCESSED_TABLE (FIELD1,CATEGORY) 
SELECT concat('DATA','-1') AS FIELD1, category  FROM #RAW_TABLE as T1
WHERE T1.CATEGORY = 'SPLIT'
UNION ALL
SELECT concat('DATA','-2') AS FIELD1, category  FROM #RAW_TABLE as T1
WHERE T1.CATEGORY = 'SPLIT'