3

I'm trying to insert data from table A to table B with query

INSERT INTO tableB(Status, UserIn, TableBID, Name)
    SELECT 
        'Active',
        UserInput,
        COALESCE(MAX(TableAID),0)+1,
        Name
    FROM 
        tableA

But I get an error:

Invalid column name 'TableAID'.

Here my TableA:

CREATE TABLE TableA  
(
    Status VARCHAR(10),
    UserInput VARCHAR(25),
    TableAID INT,
    Name VARCHAR(32)
)

And my tableB

CREATE TABLE TableB
(
    Status VARCHAR(1),
    UserIn VARCHAR(25),
    TableBID INT,
    Name VARCHAR(32)
)
5
  • Can you provide DDL of table A? Commented Apr 4, 2017 at 1:46
  • question edited @streetturtle Commented Apr 4, 2017 at 1:48
  • what do you want to do specifically? Commented Apr 4, 2017 at 1:54
  • Based on your question, your error is because you don't actually have a column called TableBID in TableB. Your DDL says you do though. You need to post the correct SQL and DDL because it is currently contradictory. You also need to post what you're actually trying to do at a higher level, i.e. load these rows into this table, generating a new id Commented Apr 4, 2017 at 1:58
  • After editing your query, do you still get same error? Commented Apr 4, 2017 at 1:59

2 Answers 2

10

You are getting that error because you are selecting from tableA, which doesn't have a TableBID column. As I understand you are trying to get the max tableBID and increment it by one for each row you insert from tableA, you could try:

INSERT INTO tableB(Status,UserIn,TableBID,Name)
SELECT 
'Active',
UserInput,
ROW_NUMBER() OVER (order by (select 1))+ (SELECT COALESCE(MAX(TableBID),0) FROM tableB ),
Name
FROM 
tableA

ROW_NUMBER() OVER (order by (select 1)) will return an incrementing number starting from 1 for each row you are inserting from tableA.

Sign up to request clarification or add additional context in comments.

3 Comments

i already edited the question. but this answer is acceptable! thank for the reply!
The usual approach is to create an identity column in the target table but this is certainly ample, as long as you don't run the query twice.
An awesome solution.
4

Two things I noticed. One it looks like for Status you are trying to insert 5 characters of data into a varchar(1) column. Maybe you should change the column length or the data you are inserting.

Second, you have multiple columns alongside an aggregate function MAX without using a GROUP BY or OVER.

1 Comment

thank you correcting me, and thank you for the advice... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.