Saya menggunakan prosedur tersimpan di bawah ini untuk memperbarui default pada kolom.
Secara otomatis menghapus default sebelumnya pada kolom, sebelum menambahkan default baru.
Contoh penggunaan:
-- Update default to be a date.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','getdate()';
-- Update default to be a number.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
-- Update default to be a string. Note extra quotes, as this is not a function.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';
Prosedur tersimpan:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- Sample function calls:
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','ColumnName','getdate()';
--exec [dbol].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';
create PROCEDURE [dbo].[ColumnDefaultUpdate]
(
-- Table name, including schema, e.g. '[dbo].[TableName]'
@TABLE_NAME VARCHAR(100),
-- Column name, e.g. 'ColumnName'.
@COLUMN_NAME VARCHAR(100),
-- New default, e.g. '''MyDefault''' or 'getdate()'
-- Note that if you want to set it to a string constant, the contents
-- must be surrounded by extra quotes, e.g. '''MyConstant''' not 'MyConstant'
@NEW_DEFAULT VARCHAR(100)
)
AS
BEGIN
-- Trim angle brackets so things work even if they are included.
set @COLUMN_NAME = REPLACE(@COLUMN_NAME, '[', '')
set @COLUMN_NAME = REPLACE(@COLUMN_NAME, ']', '')
print 'Table name: ' + @TABLE_NAME;
print 'Column name: ' + @COLUMN_NAME;
DECLARE @ObjectName NVARCHAR(100)
SELECT @ObjectName = OBJECT_NAME([default_object_id]) FROM SYS.COLUMNS
WHERE [object_id] = OBJECT_ID(@TABLE_NAME) AND [name] = @COLUMN_NAME;
IF @ObjectName <> ''
begin
print 'Removed default: ' + @ObjectName;
--print('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
EXEC('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
end
EXEC('ALTER TABLE ' + @TABLE_NAME + ' ADD DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
--print('ALTER TABLE ' + @TABLE_NAME + ' ADD DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
print 'Added default of: ' + @NEW_DEFAULT;
END
Kesalahan prosedur tersimpan ini menghilangkan
Jika Anda mencoba untuk menambahkan default ke kolom ketika sudah ada, Anda akan mendapatkan kesalahan berikut (sesuatu yang Anda tidak akan pernah lihat jika menggunakan proc yang disimpan ini):
-- Using the stored procedure eliminates this error:
Msg 1781, Level 16, State 1, Line 1
Column already has a DEFAULT bound to it.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.