How to convert empty value to nulll when insert or update

Hello
in SQL Server 2005,I want to prevent any empty value in some columns in a table in updating or inserting and if user entered the empty value in a column it must convert to null instead
ali_alannahAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

chapmandewCommented:
you could put a default value on the field...which would apply for inserts only, but you would have to write a function to do it and bind it to the column.  I dont' suggest this option.  I would write a trigger to do it.
0
BrandonGalderisiCommented:
A default value won't work because the default constraint is only used if a value is NOT specified.  Even if you supply NULL, it will use NULL.  My FIRST suggestion would be to tell whoever is inserting '' to stop.  Secondly.  If you must use trigger, you have to know whether or not you have existing triggers.  If you have existing triggers.  If you are dealing with inserts only (for now), the below should work.


The below example shows how it can be done if Field1 is your PK and Field3 is your problem field.
create trigger myIns_Trigger on myTable 
instead of insert
as
if @@rowcount=0
  return 
insert into myTable (field1, field2, field3)
select field1, field2, case field3 when '' then null else field3 end
from inserted
go
create trigger myUpd_Trigger on myTable
instead of update
if @@rowcount=0
  return 
update mt
set field2 = field2,
field3 = case field 3 when '' then null else field3 end
from myTable mt
join inserted i
on mt.field1 = i.field1

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2005

From novice to tech pro — start learning today.