Ms SQL Server 企业管理器EM: 在生成 SQL 脚本时不能为某数据库的所有表只生成"默认值约束"相关的 DDL SQL 脚本, 而不生成建表。 查询分析器QA: 可以单独生成"默认值约束"相关的 DDL SQL 脚本, 但又不能一气呵成得到所有表的"默认值约束"相关的 DDL SQL 脚本。
自己动手丰衣足食: 两种方法: 1.纯 SQL 多表 self join 实现
select'ALTER TABLE ['+ b.name +'] ADD CONSTRAINT ['+ a.name +'] DEFAULT '+ d.text+' FOR ['+ c.name +']'as[AddDefaultConstraint] ,'ALTER TABLE ['+ b.name +'] DROP CONSTRAINT ['+ a.name +']'as[DropDefaultConstraint] from sysobjects a leftjoin sysobjects b on a.parent_obj = b.id leftjoin syscolumns c on a.parent_obj = c.id and a.info = c.colid leftjoin syscomments d on a.id = d.id where a.xtype ='d' orderby b.name
2.使用 MS T-SQL 函数,少两次显式 self join 使代码简洁些
select'ALTER TABLE ['+object_name(a.parent_obj) +'] ADD CONSTRAINT ['+object_name(a.id) +'] DEFAULT '+ d.text+' FOR ['+COL_NAME(a.parent_obj,a.info) +']'as[AddDefaultConstraint] ,'ALTER TABLE ['+object_name(a.parent_obj) +'] DROP CONSTRAINT ['+object_name(a.id) +']'as[DropDefaultConstraint] from sysobjects a leftjoin syscomments d on a.id = d.id where a.xtype ='d' orderbyobject_name(a.parent_obj)