5

I am using the following query to insert values into one field in table A.

insert
into A (name)
values ('abc')
where
   A.id=B.code
   and B.dept='hr' ;

Is this query right? If not, please provide me a correct way.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38

4 Answers4

9

You should rather use UPDATE, if you want to change the value of the field in records you select using the WHERE clause.

bluish
  • 26,356
  • 27
  • 122
  • 180
htaler
  • 153
  • 1
  • 1
  • 7
6
MERGE
INTO a
USING (
  SELECT *
  FROM b
  WHERE b.dept = 'hr'
)
ON a.id = b.code
WHEN NOT MATCHED THEN
  INSERT (id, name)
  VALUES (code, 'abc')
WHEN MATCHED THEN
  UPDATE
  SET name = 'abc'
Quassnoi
  • 413,100
  • 91
  • 616
  • 614
1
INSERT INTO A (name)
SELECT name 
FROM A as a
LEFT JOIN B as b ON b.id=a.id
WHERE a.id=b.code AND b.dept='hr'

A is the first Table then B is the Second table JOIN together using LEFT JOIN then name is the column. this is what he wants to do on his question.

This is what "INSERT SELECT STATEMENT" do.

Query that can Insert while doing a select and combining a WHERE and JOIN.

INSERT TABLE1 (column1)
SELECT column1
FROM TABLE1 as a
LEFT JOIN TABLE2 as b ON b.column1=a.column1
WHERE a.column2=b.column3 AND b.column4='hr'
1

the insert part should be ok

insert
into A (name)
values ('abc')

it really depends on what you are trying to achieve with the where clause and the B table reference.

ShoeLace
  • 3,476
  • 2
  • 30
  • 44