need help with sql query to insert a new row

Farhan Jamil 421 Reputation points
2020-11-04T22:19:40.8+00:00

Hi Guys

Not sure how do i proceed here . So I want to right sql query which inserts new record

If you see in the screenshot the second row is update which i can do it. No issues at all.

Regarding the third line which is insert into an existing table i am not sure how to do it.

The issue is pkdimlocationid is identity column and rest of the values are duplicate values.

So i need help in inserting record which starts with pkdimlocationid=93.

I did start the SQL code (but i lost track)which is

SELECT TOP 2 * into #temp
FROM [DimLocation]
set identity_insert[#temp] on

insert into #temp
select max(pkdimlocationid)+1 as pkdimlocationid,
code,name,type,status='Closed',L1,L2,L3,L4,L5,L6,L7,L8,L9,StDate = '2020-11-05',EdDate='2020-12-02',updatedon=cast(getdate() as date)
from DimLocation a
where code=1
group by
code,name,type,status,L1,L2,L3,L4,L5,L6,L7,L8,L9,StDate,EdDate,updatedon

set identity_insert[#temp] off

Any help would be appreciated

Screenshot:-

37467-capture.png

Farhan Jamil

Developer technologies Transact-SQL
{count} votes

Accepted answer
  1. Farhan Jamil 421 Reputation points
    2020-11-05T00:59:30.67+00:00

    Hey Guys

    I think I figured it out how to do insert here. It drived me crazy all day. But here is the solution. This is exactly what i was looking for (see capture.png)

    insert into #temp
    select
    code
    ,Name
    ,Type
    ,Status='Close'
    ,L1
    ,L2
    ,L3
    ,L4
    ,L5
    ,L6
    ,L7
    ,L8
    ,L9
    ,StDate='2020-11-05'
    ,EdDate = '2020-12-02'
    ,UpdatedOn = cast(getdate() as date)
    from #temp
    where pkDimLocationId in(1)

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Farhan Jamil 421 Reputation points
    2020-11-04T22:59:06.683+00:00

    Hi Erland

    This is just a sample. I have about 700 records in the data in dimlocation which i have to update.

    Inorder to make sure I am preparing my sql statement correct,I am taking the two sample into a temp table and then preparing my insert statement to make sure that it is correct before running the actual insert statement for all records.

    The issue is if you can see in the screenshot , I have pkdimlocationid which is an identity column and apart from that none of the columns are unique which i can use to insert the record.

    The first two records are you see in the screenshot is already present in the database. I need to insert the third one.

    here is another screenshot . This is what i am trying to achieve. So i have to create a script to update 700 records something in this manner.

    37552-capture-1.png

    Henceforth I started taking all this into a temp table and then updating the record.

    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.