Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble setting a computed column as not Null

I'm having problems setting a computed column as not null.

What I want to achieve is C001,C002..., etc. and at the same time set it as not null.

I have read on a forum that this can be achieved by using the default value 0 for NULL values.
E.g., ISNULL(Price + Taxes, 0)

I have tried to apply to this formula:

('C'+right('000'+CONVERT([varchar](3),[ID],(0)),(3)))

But it didn't seem to work. Can anyone tell me what am I missing?

ALTER CreditCard accountNo AS ISNULL('C'+right('000'+CONVERT([varchar](3),[idCreditCard],(0)),(3)),0)
like image 299
Keenlearner Avatar asked Jun 21 '12 07:06

Keenlearner


People also ask

How do you define a column as not NULL?

By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.

Can a column defined with NOT NULL constraint?

If you place a NOT NULL constraint on a column (and no default value is specified), you must enter a value into this column when you insert a row or update that column in a row. If you do not enter a value, the database server returns an error, because no default value exists.

Can a column be unique and not NULL?

Unique fields in SQL Server are created using unique constraints or unique indexes, furthermore, each unique constraint uses a unique index. Regardless of using unique constraint or unique index, the field can accept null values, however the uniqueness will result in only accepting a single row with null value.


1 Answers

I've finally found the solution to my problem!

The correct query should be:

ALTER TABLE CreditCard ADD accountNo AS ISNULL('C'+right('000'+CONVERT([varchar](3),[idCreditCard],(0)),(3)),0)

Thanks for the help guys!

like image 89
Keenlearner Avatar answered Sep 28 '22 08:09

Keenlearner