November 3, 2011 at 8:31 am
Hi,
I need to create an new column in a table
with this statement:
ALTER TABLE dbo.CONTRIBUINTES ADD
DT_CADASTRAMENTO datetime NULL
GO
ALTER TABLE dbo.CONTRIBUINTES ADD CONSTRAINT
DF_CONTRIBUINTES_DT_CADASTRAMENTO DEFAULT convert(varchar,getdate(),120) FOR DT_CADASTRAMENTO
GO
But, before create it, i need to know if the column is not already created.
If the column is already in the table, then it does not performe the operation.
Can someone help?
Thank you
November 3, 2011 at 8:38 am
Hi,
Try something like this:
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'CONTRIBUINTES' AND COLUMN_NAME = 'DT_CADASTRAMENTO')
ALTER TABLE dbo.CONTRIBUINTES ADD
DT_CADASTRAMENTO datetime NULL
ALTER TABLE dbo.CONTRIBUINTES ADD CONSTRAINT
DF_CONTRIBUINTES_DT_CADASTRAMENTO DEFAULT convert(varchar,getdate(),120) FOR DT_CADASTRAMENTO
I've not tested it but it should get you going. INFORMATION_SCHEMA contains lots of useful information.
Thanks,
Simon
November 3, 2011 at 8:41 am
I am sorry. It's in SQL Server 2000 not in 2005...
My mistake (the post is in the rong place) 🙁
November 3, 2011 at 8:42 am
i usually use dynamic sql for the command, as if i'm adding a table that doesn't exist, the script will fail validation.
IF EXISTS(SELECT 1
FROM sys.objects objz
INNER JOIN sys.columns colz
ON objz.object_id = colz.object_id
WHERE SCHEMA_NAME(objz.schema_id) = 'dbo'
AND objz.name = 'CONTRIBUINTES'
AND colz.name = 'DT_CADASTRAMENTO')
exec ('ALTER TABLE dbo.CONTRIBUINTES
ADD DT_CADASTRAMENTO DATETIME NULL')
--edit--
2000 version
IF EXISTS(SELECT 1
FROM sysobjects objz
INNER JOIN syscolumns colz
ON objz.id = colz.id
WHERE USER_NAME(objz.uid) = 'dbo'
AND objz.name = 'CONTRIBUINTES'
AND colz.name = 'DT_CADASTRAMENTO')
exec ('ALTER TABLE dbo.CONTRIBUINTES
ADD DT_CADASTRAMENTO DATETIME NULL')
Lowell
November 3, 2011 at 8:44 am
In SQL server 2000 i can do like this:
if not exists (select * from syscolumns where name ='dt_cadastramento')
begin
alter statement here
end
correct?
November 3, 2011 at 8:44 am
river1 (11/3/2011)
I am sorry. It's in SQL Server 2000 not in 2005...My mistake (the post is in the rong place) 🙁
You should still be able to get at INFORMATION_SCHEMA though...
http://msdn.microsoft.com/en-us/library/aa933204(v=sql.80).aspx
November 3, 2011 at 9:07 am
Thank you very much guys
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply