I am modifying a SQL table through C# code and I need to drop a NOT NULL constraint if it exists. How do I check to see if it exists first?
A:
I'm not sure about your business rules, so I could be wrong, but what you are proposing sounds like a bad idea.
If the NOT NULL constraint shouldn't exist, then remove it from the DB. If it should exist, program around it.
If you actually do need to implement DDL to change tables, I'd write a stored procedure to do and call the stored procedure from C#.
mson
2008-12-09 15:35:06
I am dynamically updating a table based on selected values. The end-user is defining this table so we are giving them tools (that they understand) to be able to do this.
Scott
2008-12-09 15:40:42
I stand corrected.
mson
2008-12-09 15:44:28
no need to be corrected! That was good advice.
Scott
2008-12-09 16:09:29
+10
A:
select is_nullable
from sys.columns
where object_id = OBJECT_ID('tablename')
and name = 'columnname';
Dave Markle
2008-12-09 15:37:34
+1
A:
Well, you could check syscolumns.isnullable
flag? Or more recently:
COLUMNPROPERTY(@tableId, 'ColumnName', 'AllowsNull')
Where @tableId is OBJECT_ID('TableName')
Marc Gravell
2008-12-09 15:37:57
A:
you can with the use of COLUMNPROPERTY:
SELECT COLUMNPROPERTY( OBJECT_ID('schemaName.TableName'), 'ColumnName', 'AllowsNull')
Mladen Prajdic
2008-12-09 15:40:23
+1
A:
execute this SQL Statement:
select * from information_schema.columns c
inner join information_schema.tables t on c.table_catalog = t.table_catalog and t.table_schema = c.table_schema and t.table_name = c.table_name
where c.table_name = 'Categories' and c.Is_nullable = 'NO'
and then execute the ALTER statement that removes the "not null" constraint
Rick Kierner
2008-12-09 15:40:34