I found this and edited it down to show the primary key code.
The same is possible for all constraints but this is the simplest:
select CASE WHEN tc.Constraint_Name IS NULL THEN ''
ELSE 'ALTER TABLE '
+ so.Name + ' ADD CONSTRAINT '
+ tc.Constraint_Name + ' PRIMARY KEY '
+ ' (' + LEFT(j.List, Len(j.List)-1) + ')'
END
from sysobjects so
left join
information_schema.table_constraints tc
on tc.Table_name = so.Name
AND tc.Constraint_Type = 'PRIMARY KEY'
cross apply
(select '[' + Column_Name + '], '
FROM information_schema.key_column_usage kcu
WHERE kcu.Constraint_Name = tc.Constraint_Name
ORDER BY
ORDINAL_POSITION
FOR XML PATH('')) j (list)
where xtype = 'U'
AND name NOT IN ('dtproperties')
and tc.TABLE_NAME = @tablename;
As you can see, it is not a simple task :S