重构许多数据库表中的重命名字段
我面临着重命名一个字段,其中相同的字段名在许多表中复制。
寻找一个脚本或免费/低成本工具来遍历所有表,如果 fieldA 存在,则将其重命名为 fieldB。
谢谢
I am faced with renaming a field where the same fieldname is replicated across many tables.
Looking for a script or free/low cost tool which will go through all the tables and if fieldA exists, rename it to fieldB.
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 SQL Server 元数据表来创建符合您目的的动态 SQL 语句。
对于可用表的列表,您可以使用 sys.tables 作为表列表,使用 sys.columns 作为列列表。使用这些表,您可以创建一个 sql 语句表。要执行动态 sql,您需要 sp_executesql 存储过程。
这是一个示例代码,只是为了展示如何使用元数据表和 sp_executesql:
请注意,我使用了其他我更喜欢的元数据表。您也可以使用游标来运行查询返回的所有脚本。
You can use SQL Server metadata tables to create dynamic sql statements for your purpose.
For list of available tables you can sys.tables for list of tables and sys.columns for list of columns. using these tables you can create a table of sql statements. For executing dynamic sqls you need to sp_executesql stored procedure.
This is a sample code just to show how to use metadata tables and sp_executesql:
And note that I used other metadata tables which I am more comfortable with. also you may use a cursor to run all the scripts returned by query.
如果您还没有查看过 VS2010 中的数据库项目类型,请查看一下。它具有许多功能,使数据库重构比工作 SQL Server Management Studio 更容易。
例如,如果您重命名一列,则会出现引用旧列名的所有 FK 的构建错误。它会进行大量的构建时验证,以确保您的数据库对象不会引用不再存在的对象。由于所有数据库对象都仅保存为文本文件,因此重命名等操作几乎只是搜索/替换。
此外,它还有非常方便的“同步”功能,可以比较数据库项目脚本和数据库项目脚本。数据库,生成 DIFF 报告,并生成脚本以在两者之间移动选定的更改(DB 项目到 SQL Server,或反之亦然)。
话虽如此,它不会自动为您进行重命名——换句话说,当您重命名列时,它不会修复整个项目中对该列的所有引用。但是,如果您犯了一个错误,那么在验证数据库结构时就会出现构建错误。这样至少可以很容易地找到你需要改变的地方。
Take a look at the Database project type in VS2010, if you haven't already. It has a lot of features that make DB refactoring easier than working SQL Server Management Studio.
For example if you rename a column, it will give you build errors for all the FKs that reference the old column name. And it does a lot of build-time validation to make sure your database objects don't reference objects which no longer exist. And because all of the database objects are just kept as text files, actions like rename are pretty much just search/replace.
Also, it has very handy "sync" feature which compares the DB project scripts & databases, generates a DIFF report, and generates the scripts to move selected changes between the two (either DB project to SQL Server, or vice versa).
Having said all that, it won't automatically do the renames for you -- in other words, when you rename a column it won't fix up all references to that column throughout the project. But if you make a mistake you will get build errors when it validates the database structure. So at least makes it easy to find the places that you need to change.
如果您使用的是 Azure SQL Server,则可以将 Sam 的答案与 sp_rename 的另一个输入参数 @objtype = 'COLUMN' 结合使用。
If you're using Azure SQL Server, you can use Sam's answer with another input parameter to sp_rename, @objtype = 'COLUMN'.