How to use AS to substitute a value when inserting based on another record

Robert Lassetter 1 Reputation point
2022-02-24T02:45:27.187+00:00

I want to add missing records by copying other records.

If a record is missing Field2 value of '033', I want to copy a record that has Field2 = '012' and just replace it with '033'

My only error is using AS. Appears I cannot substitute a value.
Field1 and Field2 are Key.

Insert into Table (Field1,'033' as Field2,Field3)
select * from (select * from Table) as tmp)
where not exist (select TOP 1 Field2 from table where Field2='012')

Developer technologies | Transact-SQL
{count} votes

2 answers

Sort by: Most helpful
  1. Naomi Nosonovsky 8,431 Reputation points
    2022-02-24T03:07:50.977+00:00

    Try:

    ;with cte as (select Field1, '033' as Field2, Field3 from myTable t where not exists (select 1 from myTable t2 where Field2 = '012') -- what about field1 - do we want correlated subquery, do we want just one row or many?
    
    insert into table (field1, field2, field3) -- first comment insert portion and verify you got expected results before actual insert
    select Field1, Field2, Field3 from cte
    
    0 comments No comments

  2. LiHong-MSFT 10,056 Reputation points
    2022-02-24T09:39:16.59+00:00

    Hi @RobertLassetter-8330
    Insert into table( column list )
    For column list ,we can't use '033' as Field2 here.
    We can use '033' as Field2 in the select clause.Please check the code that Viorel commented above.

    Best Regards
    LiHong

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.