Wednesday, March 28, 2012

How to assign a column's value to another column's default

I got a table. i m using SQL 2005.

tblMy
--
col1 varchar(10) NotNull
col2 varchar(10) AllowNulls
col3 varchar(10) AllowNulls

Question: How to assign the col1's value to col3's default value. If user enters a data to col3 , its ok , but if don't SQL will automatically insert the value of col1 to col3.

Happy Coding....

I don't think a default constraint will work for this. You could use a trigger though.

Alteratively, you could mimic this behavior with a view, something like:

create view myview as select col1, col2, coalesce(col3,col1) from mytable

|||

View may be solution to another problem, but not mine. But trigger is a good idea, i thought before , but im inexprienced on triggers. I'll try to learn as quick as i can. Thanks for your post.

Happy Coding...

|||

I found the answer of my own question:

To do this, i use "Computed Column Specification" (Formula Section). Obviously it is surprising no one answered this simple question except 1 person. Interesting

Happy Coding...

sql

No comments:

Post a Comment