是否可以同时向多个表添加列?
我正在使用 SQL Server。我想将名为 [DateCreated] 的单个列添加到多个表中。是否可以通过一条语句将此列添加到数据库中的所有表中?
我偶然发现了 Joe Steffaneli 的一个答案,他在其中建议了一个查询,该查询又返回包含 Alter table 语句的行。 查询如下:
select 'alter table ' + quotename(s.name) + '.' + quotename(t.name) + ' add [DateModified] datetime'
from sys.columns c
inner join sys.tables t
on c.object_id = t.object_id
inner join sys.schemas s
on t.schema_id = s.schema_id
left join sys.columns c2
on t.object_id = c2.object_id
and c2.name = 'DateModified'
where c.name = 'DateCreated'
and t.type = 'U'
and c2.column_id is null /* DateModified column does not already exist */
有什么方法可以执行返回的行吗?对不起英语。
I am using SQL Server. I want to add a single column named [DateCreated] to multiple tables. Is it possible that with a single statement I could add this column to all the tables in my database?
I stumble upon an answer by Joe Steffaneli in which he suggested a query which in turn returns rows consisting Alter table statements.
Query is as follows :
select 'alter table ' + quotename(s.name) + '.' + quotename(t.name) + ' add [DateModified] datetime'
from sys.columns c
inner join sys.tables t
on c.object_id = t.object_id
inner join sys.schemas s
on t.schema_id = s.schema_id
left join sys.columns c2
on t.object_id = c2.object_id
and c2.name = 'DateModified'
where c.name = 'DateCreated'
and t.type = 'U'
and c2.column_id is null /* DateModified column does not already exist */
Is there any way that I can execute returned rows? Sorry for English.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你可能需要这样的东西。在运行脚本之前检查脚本是否执行了您想要的操作(添加默认值为
getdate()
的非空列)!You probably need something like this. Check that the script does what you want before running it (adds a non null column with a default value of
getdate()
)!您可以使用此查询
我在此查询中使用 where 子句(可选)来查找所有具有 ID 的表并向其中添加新字段。
您可以更改 where 子句,例如查找具有 BusinessId 列的所有表并添加新字段或删除 where 子句并为所有表添加
You can use this query
I use the where clause in this query (it is optional) to find all tables that have ID and add the new field to them.
you can change where clause for example find all tables that have BusinessId column and add new filed or remove where clause and add for all tables
这个存储过程工作正常
This stored procedure works fine
不,没有任何一条语句可以将列添加到数据库中的所有表中。
下次请用您正在使用的 RDBMS 标记您的问题。如果有办法的话,我们将无法在不知道您正在使用哪个数据库系统的情况下向您提供命令。
No, there is no single statement that will add a column to all the tables in your database.
Next time please tag your question with the RDBMS you're using. If there were a way, we wouldn't be able to give you the command without knowing which database system you are using.