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..
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 :)
CodePudding user response:
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.
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.
CodePudding user response:
I can't post comments yet but I think it's a duplicate of this:
How can I do 'insert if not exists' in MySQL?
and on this topic there is a good answer: https://stackoverflow.com/a/1361368/15670345
or use WHERE NOT EXISTS
example : [click]