0

I want Chack If Value exists in coulmn, If value exist do not insert to table. If not exist insert to table a new data.

I tried this but not works..

SQL QUERY

SQL ERROR

my code in node.js `

//add new meeting
async function addNewMeeting(meeting: Meeting): Promise<Meeting>{
  const sql = `INSERT INTO meetings Values (
    DEFAULT,
    ${meeting.meeting_code},
    '${meeting.meeting_start_date}',
    '${meeting.meeting_end_date}',
    '${meeting.meeting_description}',
    '${meeting.meeting_room}'
    )`;
  const result:OkPacket = await dal.execute(sql);
meeting.id = result.insertId;
return meeting;
}

`

I tried to chack if the value - '2022-10-15 07:03:42' exist or not. If not exists insert to table a new data. if exist send a error that cannot insert a new meeting because there is already meeting at this time.

thanks :)

Itay999
  • 1
  • 2
  • 2
    Does this answer your question? [How can I do 'insert if not exists' in MySQL?](https://stackoverflow.com/questions/1361340/how-can-i-do-insert-if-not-exists-in-mysql) – Dakeyras Nov 05 '22 at 22:07

1 Answers1

0

You can solve this at the SQL level by using the keyword UNIQUE when defining that column in the table. This will prevent you from being able to insert duplicate values.

SQL UNIQUE

Note that this will throw an error and depending on the package you are using to connect to your database, you might need some error handling.

Alternatively in your javascript you can select all values in the column that should be unique, and then only proceed with the insertion code if there is not a match.

Dakeyras
  • 1,829
  • 5
  • 26
  • 33