15

I have a column in my DB which is currently defined as NOT NULL. I would like to update this column to allow NULLs.

I have the following script to do this however I would like to check first if the column is already NULL (or NOT NULL), as it may have been changed previously.

 ALTER TABLE [dbo].[aud] ALTER COLUMN [actname] nvarchar(50) NULL 

Any help appreciated.

1
  • 7
    Why do you want to check? If the column is already nullable, you can safely run your alter statement, it will have no effect but not give any error either. Commented Jun 17, 2013 at 13:49

3 Answers 3

14

Use COLUMNPROPERTY to get column property . You may write something like

SELECT COLUMNPROPERTY(OBJECT_ID('dbo.aud'),'actname','AllowsNull') AS 'AllowsNull'; 

For more information please visit this link

Sign up to request clarification or add additional context in comments.

2 Comments

+1 Neat. Is this more efficient than the sys tables? Not that efficiency will be a massive overhead in this scenario.
I think so though i am not 100% sure ..:)
7
select is_nullable from sys.columns c inner join sys.tables t on t.object_id = c.object_id where t.name = 'aud' and c.name = 'actname' 

Will give you a BIT representing whether it is nullable or not.

So you could switch on this like

IF EXISTS(SELECT * from sys.columns c inner join sys.tables t on t.object_id = c.object_id where t.name = 'aud' and c.name = 'actname' AND is_nullable = 1) BEGIN --What to do if nullable END ELSE BEGIN --What to do if not nullable END END 

That of course assumes that the table and column exist at all...

Comments

3

There isn't really a need to do that, because if it's already Nullable, changing a column from Nullable to Nullable will have no negative effect.

However you can do it with this query:

SELECT is_nullable FROM sys.columns WHERE object_id=object_id('YourTable') AND name = 'yourColumn' 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.