我可以在 SQL Server 2008 中编写 DDL 触发器来根据列名自动创建键吗?
我从未编写过 DDL 触发器,但我的理解是它们在架构更改时运行 SQL。我希望简化重复性任务。我不确定它们是否真的只是为了审计目的而设计的。
- 对于第一个序数位置的 int 字段 [id]:
- 将其设为主键
- 设置身份种子/增量为1
- 对于第二个序数位置的 varchar 字段 [name]:
- 使其成为唯一的密钥
基本上,问题是:SQL Server 2008 中的 DDL 触发器是否适合我想要做的事情? (而且,如果您已经这样做并且有 sql 代码,可以将其粘贴进去吗?)
I've never written a DDL trigger, but my understanding is that they run SQL when the schema changes. I am looking to streamline the repetitive tasks. I'm not sure if they are really only designed for auditing purposes.
- For an int field [id] in the first ordinal position:
- make it the primary key
- set the identity seed/increment is 1
- For a varchar field [name] in the second ordinal position:
- make it a unique key
Basically, the question is: Are DDL triggers in SQL Server 2008 a good match for what I want to do? (And, if you already do this and have the sql code right there, could you please paste it in?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无 DDL 触发器不太适合您想要执行的操作。
DDL 触发器在表创建之后运行。
列不能追溯添加
identity
属性,这意味着您的触发器需要使用动态 SQL 来立即删除新创建的表并重新创建它。即使假设这只是针对个人项目,这样您的其他开发人员就不会担心意外,也不会担心生成
create
脚本的低效率方面,无论您尝试还是很难做到稳健并从头开始或解析 CommandText 作为起点。如果这对您来说是常见模式,那么您可能需要研究在 SSMS 的模板资源管理器中创建自定义
CREATE TABLE
模板。No DDL triggers are not a good match for what you want to do.
DDL Triggers run after the table is already created.
A column cannot have the
identity
property added on retrospectively which would mean that your trigger would need to use dynamic SQL to immediately drop the newly created table and recreate it.Even assuming that this is just for a personal project so you don't have fellow developers to worry about surprising and are not bothered about the inefficiency aspect generating the
create
script would be difficult to do robustly whether you try and start from scratch or parse theCommandText
as a starting point.If this is a common pattern for you then you might want to investigate creating a custom
CREATE TABLE
template in SSMS's template explorer.