I added a checking on a Varchar column that I want to modify its LENGTH
, and its default value
table = EX_EMPLOYEE
Column = TV_CODE
length =10
My problem : I made 3 blocks to change the length then to drop the default value and add a new one. can I do that in one block ? is there alternative way for the below its a really long code can I make better checking with less condition and coes ?
BEGIN
DECLARE @OLD_LENGTH numeric(4)
DECLARE @isnull numeric(4)
DECLARE @null_value varchar(10)
SELECT @OLD_LENGTH= c.length,
@isnull = c.isnullable
FROM syscolumns c
WHERE c.id = OBJECT_ID('EX_EMPLOYEE') AND c.name = 'TV_CODE'
if @isnull =1
select @null_value='NULL'
else
select @null_value='NOT NULL'
IF @@ROWCOUNT =0
begin
EXECUTE ('ALTER TABLE EX_EMPLOYEE ALTER COLUMN TV_CODE VARCHAR(11) '+@null_value)
end
if @OLD_LENGTH <11
EXECUTE ('ALTER TABLE EX_EMPLOYEE ALTER COLUMN TV_CODE VARCHAR(11)'+ @null_value)
END
GO
begin
DECLARE @df_value varchar(500)
select @df_value = d.name from sys.all_columns c join sys.tables t on t.object_id = c.object_id join sys.schemas s on s.schema_id = t.schema_id
join sys.default_constraints d on c.default_object_id = d.object_id
where t.name = 'EX_EMPLOYEE' and c.name = 'TV_CODE'
if @df_value is not null
begin
EXECUTE ('ALTER TABLE EX_EMPLOYEE DROP CONSTRAINT '+ @df_value)
end
end
go
IF EXISTS (SELECT 1 FROM sys.all_columns c WHERE c.object_id = OBJECT_ID('EX_EMPLOYEE')
AND c.name = 'TV_CODE')
and NOT EXISTS(select * from sys.all_columns c join sys.tables t on t.object_id = c.object_id join sys.schemas s on s.schema_id = t.schema_id
join sys.default_constraints d on c.default_object_id = d.object_id
where t.name = 'EX_EMPLOYEE' and c.name = 'TV_CODE')
BEGIN
EXECUTE ('ALTER TABLE EX_EMPLOYEE ADD DEFAULT ''A'' for TV_CODE')
END
GO