/* for the google index */
ALTER TABLE
DEFAULT COLUMN
DEFAULT VALUE
I've worked out several stored procedures for altering the default column
values in a table. They were compiled from books and code snippets found
here. It was a pain to work out so I've decided to share my work and
research here. This post is just my way of saying thanks to several others
here for posting with their wisdom and intelligence.
Michael
simpsonAT(dot)cts(dot)com
This procedure gets the constraint name. If you use the design view to
setup a default value, you won't know the system assigned constraint name.
This proc makes it an non issue. This code was gleened from this news
group.
CREATE PROCEDURE [DBO].[GetConstraintName]
(
@tablename sysname,
@columnName sysname,
@constraintName sysname OUTPUT
)
as
SELECT
@constraintName = o1.name
FROM
sysobjects o1
INNER JOIN
syscolumns c ON o1.id = c.cdefault
INNER JOIN
sysobjects o2 ON o1.parent_obj = o2.id
WHERE (o2.name = @tablename) AND (c.name = @columnName)
This procedure changes the default value for a column that is a numeric. It
uses the previously define stored procedure to get the constraint name. A
text version of this procedure can be created by removing the cast, defining
the input parameter "newConstraint" as varchar(255).
CREATE PROCEDURE [dbo].[ChangeIntConstraint]
(
@tableName sysname,
@columnName sysname,
@newConstraint int
)
AS
Declare @conName sysname
exec GetConstraintName @tableName, @columnName, @constraintName = @conName
OUT
declare @sql nvarchar(1024)
set @sql = 'ALTER TABLE ' + @tableName + ' drop constraint ' + @conName
exec(@sql)
set @sql = 'ALTER TABLE ' + @tableName + ' ADD CONSTRAINT ' + @conName + '
DEFAULT (' + CAST(@newConstraint AS varchar(255)) + ') FOR ' + @columnName
exec(@sql)