如何复制 SQL table 中的一行并更改其中一个列值?

How do you copy a row in a SQL table and alter one of the column values?

this question 的答案几乎回答了我的问题,但不完全是。我如何打开它:

col0  col1 col2
data0 a    foo
data1 b    foo
data2 c    fee
data3 d    fee

进入这个? (仅复制 foo 行)

col0  col1 col2
data0 a    foo
data1 b    foo
data2 c    fee
data3 d    fee
data0 a    bar
data1 b    bar

其中 bar 来自语句,而不是数据,原始 table 有 2 个新行。

一个选项,union all

select col0, col1, col2
from yourtable
union all
select col0, col1, 'bar'
from yourtable
insert into T (col0, col1, col2)
select col0, col1, 'bar'
from T

如果 "copy" 你的意思是 select 那么联合会像其他答案一样工作,或者你可以试试这个:

select col0, col1, case when num = 0 then col2 else 'bar' end as col2
from T, (select 0 as num union all select 1) as dup

假设您只需要这两个硬编码字符串的结果,以下查询将为您提供。

    SELECT
        col0,
        col1,
        'foo'
    FROM MyTable
UNION ALL
    SELECT
        col0,
        col1,
        'bar'
    FROM MyTable;

更实际的方案是使用临时 table 这样您就不会为每个方案重复查询。

CREATE TABLE #Options
(
    col2 VARCHAR(50)
);

INSERT INTO #Options VALUES ('foo'), ('bar');

SELECT
    col0,
    col1,
    #Options.col2
FROM MyTable
CROSS JOIN #Options;
select col0, col1, col2
from yourtable
union all
select col0, col1, 'bar'
from yourtable
where col2 = 'foo'