Avoid inserting a particular value into sql table

541 Views Asked by At

I am not sure, if this can be achieved in SQL.

INSERT INTO table_name (column1, column2, column3) 
VALUES (value1, value2, 999);

If the user tries to insert 999 in column3, convert it to null or avoid inserting it.

I am trying to find if I can find any solution from SQL Server side.

2

There are 2 best solutions below

2
Mark Kram On BEST ANSWER

How about using a Check Constraint:

ALTER TABLE table_name
ADD CHECK (column3<>999);
0
Tanner Clark On

You cannot case the 999 in the insert statement. It really depends on the implementation. Is this strictly in the Database? Is it being called with a java/python/scala library? In the database, I would recommend the following:

set @value1 = val1;
set @value2 = val2;
set @value3 = if(val3=999,NULL,val3);

INSERT INTO table_name (column1, column2, column3) 
VALUES (@value1, @value2, @value3);

If outside the Database, just use the same logic.