一气呵成得到 MSSQL DB 中所有表的字段默认值约束的 DDL SQL 脚本

Ms SQL Server
企业管理器EM:
在生成 SQL 脚本时不能为某数据库的所有表只生成"默认值约束"相关的 DDL SQL 脚本,
而不生成建表。
查询分析器QA:
可以单独生成"默认值约束"相关的 DDL SQL 脚本,
但又不能一气呵成得到所有表的"默认值约束"相关的 DDL SQL 脚本。

自己动手丰衣足食:
两种方法:
1.纯 SQL 多表 self join 实现

None.gifselect 'ALTER TABLE [' + b.name + '] ADD CONSTRAINT [' + a.name + '] DEFAULT ' + d.text + ' FOR [' + c.name + ']' as [AddDefaultConstraint]
None.gif,
'ALTER TABLE [' + b.name + '] DROP CONSTRAINT [' + a.name + ']' as [DropDefaultConstraint]
None.gif
from sysobjects a
None.gif
left join sysobjects b on a.parent_obj = b.id
None.gif
left join syscolumns c on a.parent_obj = c.id and a.info = c.colid
None.gif
left join syscomments d on a.id = d.id
None.gif
where a.xtype = 'd'
None.gif
order by b.name

2.使用 MS T-SQL 函数,少两次显式 self join 使代码简洁些

None.gifselect '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]
None.gif,
'ALTER TABLE [' + object_name(a.parent_obj) + '] DROP CONSTRAINT [' + object_name(a.id) + ']' as [DropDefaultConstraint]
None.gif
from sysobjects a
None.gif
left join syscomments d on a.id = d.id
None.gif
where a.xtype = 'd'
None.gif
order by object_name(a.parent_obj)


 

转载于:https://www.cnblogs.com/Microshaoft/archive/2005/08/17/217103.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值