Wednesday, 15 August 2007

Check/find default

If you know the name of the default and you always have good naming convention that include table and column name in your default name, then you can simple check against the sysobjects table to find out if a default exists:

SELECT * FROM SysObjects O WHERE name = 'DF_DEFAULTNAME' AND xtype = 'D'

If you want to know a particular column has a default defined or not:

SELECT * FROM SysObjects O INNER JOIN SysColumns C ON O.ID=C.ID
INNER JOIN SysConstraints T ON C.CDEFAULT = T.CONSTID
WHERE ObjectProperty(O.ID,'IsUserTable')=1
AND O.Name='TableName'
AND C.Name='ColumnName'

If the name of the default is what you are after:

SELECT O2.Name FROM SysObjects O INNER JOIN SysColumns C ON O.ID=C.ID
INNER JOIN SysConstraints T ON C.CDEFAULT = T.CONSTID
INNER JOIN SysObjects O2 ON T.CONSTID = O2.ID
WHERE ObjectProperty(O.ID,'IsUserTable')=1
AND O.Name='TableName'
AND C.Name='ColumnName'

No comments:

Post a Comment