Shekh Adnan
Shekh Adnan

Reputation: 73

How can I store a SELECT query result(one column) into a new table's column?

This is my query:-

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

After executing it, I'm getting this output:

enter image description here

This is my new table:

CREATE TABLE AddData(Name VARCHAR(MAX))

I want to insert the result generated by the SELECT query into my new table AddData. Can you help me do this?

Upvotes: 0

Views: 1640

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271151

You would use 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;

I would instead suggest writing the logic as :

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

You won't have to create the table first.

Also, if you do want to remove duplicates then use select distinct. It is not clear if you are using union intentionally to remove duplicates or just to combine two separate subqueries.

Upvotes: 3

Related Questions