I am currently trying to rename all of the Default constraints in my database to fit in with my naming convention of DF_+TableName+ColumnName. Since there are over 300 of the things, I don't particularly fancy doing them all manually.
I was hoping to use something like...
Code:
--Declare the variables
DECLARE @defname VARCHAR(100), @tblname VARCHAR(100), @colname VARCHAR(100), @cmd VARCHAR(1000)
--Set the table name
SET @tblname = (SELECT object_name(parent_obj) FROM sysobjects
LEFT JOIN sys.columns ON sys.columns.object_id = sysobjects.id
INNER JOIN sysconstraints ON sysobjects.id = sysconstraints.constid
WHERE sysobjects.xtype = 'D')
--Set the column name
SET @colname = (SELECT name FROM sys.columns
INNER JOIN sys.tables ON sys.tables.object_id = sys.columns.object_id
WHERE sys.tables.name = @tblname)
--Set the default constraint
SET @defname = (SELECT name FROM sysobjects JOIN sysconstraints
ON sysobjects.id = sysconstraints.constid
WHERE object_name(sysobjects.parent_obj) = @tblname
AND sysobjects.xtype = 'D'
AND sysconstraints.colid = (SELECT colid FROM syscolumns
WHERE id = object_id(@tblname) AND
name = @colname))
--Set the renaming
SET @cmd = EXEC sp_rename +@defname+, 'DF_'+@tblname+'_'+@colname+, 'OBJECT'
--Execute the renaming
EXEC(@cmd)
I know that the above is not correct in any way, but it is how far I have got before I got really stuck! And I thought it might help you see what I was trying to get at...
Any clues?