Thursday, March 31, 2011

How to insert with where clause

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. It's really urgent. Thanks in advance.

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

    paxdiablo : Or 'upsert' if you're using one of those new-fangled databases :-)
  • 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'
    
  • 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.

0 comments:

Post a Comment