如何将SELECT查询结果(一列)存储到新表的列中?

时间:2018-07-21 12:15:56

标签: sql sql-server

这是我的查询:-

select 
    (FirstName + ' ' + Lastname) as [Name] 
from 
    c_client 
where 
    MiddleInitial is null

union

select 
    (FirstName + ' ' + MiddleInitial + '''' + Lastname) as [Name] 
from 
    c_client 
where 
    MiddleInitial is not null

执行后,我得到以下输出:

enter image description here

这是我的新桌子:

CREATE TABLE AddData(Name VARCHAR(MAX))

我想将SELECT查询生成的结果插入到新表AddData中。你能帮我做到吗?

1 个答案:

答案 0 :(得分:3)

您将使用insert

insert into AddData (Name)
    Select (FirstName + ' ' + Lastname) as [Name]
    from c_client
    where MiddleInitial IS NULL
    UNION 
    Select (FirstName + ' ' + MiddleInitial +''''+ Lastname) as [Name] 
    from c_client
    where MiddleInitial IS NOT NULL;

我建议将逻辑写为:

select (FirstName +
        coalesce(MiddleInitial + '''', '') +
        ' ' +
        Lastname
       ) as Name
into AddData
from c_client c;

您不必先创建表。

此外,如果您确实要删除重复项,请使用select distinct。目前尚不清楚您是故意使用union来删除重复项还是只是将两个单独的子查询组合在一起。