• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 363
  • Last Modified:

determine default constraint on a col and delete it

Hi!

I'll be writing a script, where given a col name, I need to determine the name of the default constraint (if any) that exists on it, and delete it. At present, I am using the foll query to determine the constraint name:


select t_obj.name as TABLE_NAME
,c_obj.name as CONSTRAINT_NAME
,col.name as COLUMN_NAME
from
sysobjects c_obj
join sysobjects t_obj on c_obj.parent_obj = t_obj.id
join sysconstraints con on c_obj.id = con.constid
join syscolumns col on t_obj.id = col.id and con.colid = col.colid
where t_obj.name = '<table name>'
and c_obj.xtype = 'D'
and col.name = '<column name>'

if i was running this manually from the query analyzer, then what i could do is, run it, then see which constraints are returned, and then maybe run another "ALTER TABLE DROP CONSTRAINT" query ... but from a script, i cant do that since i dont know the name of the constraint unless i "look" at the results returned

can anyone help me?

thanks :)
muskad202
0
muskad202
Asked:
muskad202
1 Solution
 
Ved Prakash AgrawalDatabase Consultant/Performance ArchitectCommented:
HI tried to place the result  into temp table and use the while loop and place the alter command inside loop.

you can dynamic query place inside while loop
and then you can place logic inside that


ved
0
 
muskad202Author Commented:
Hi!

can u tell me the syntax for using a while loop in TSQL?

thanks,
muskad202
0
 
Scott PletcherSenior DBACommented:
You don't really need a loop; a single dynamically-executed command should be
able to handle almost all table defaults.


DECLARE @tableName NVARCHAR(100)
DECLARE @columnName NVARCHAR(100)
SET @tableName = N'<table name>'
SET @columnName = N'<column name>'  --or N'ALL' to drop all defaults on table


DECLARE @sqlCmd VARCHAR(8000)
SET @sqlCmd = ''

SELECT @sqlCmd = @sqlCmd + 'ALTER TABLE ' +
    CAST(OBJECT_NAME(id) AS VARCHAR(100)) + ' DROP CONSTRAINT ' +
    CAST(OBJECT_NAME(constId) AS VARCHAR(100)) + ';' +
    CASE WHEN @columnName = N'ALL' THEN
        ' /* ' + CAST(COL_NAME(id, ColId) AS VARCHAR(100)) + ' */'
         ELSE '' END + CHAR(13)
FROM sysconstraints WITH (NOLOCK)
WHERE OBJECTPROPERTY(constId, 'IsDefaultCnst') = 1 AND
    id = OBJECT_ID(@tableName) AND
    (@columnName = N'ALL' OR COL_NAME(id, colId) = @columnName)

PRINT @sqlCmd  --optional
EXEC (@sqlCmd)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now