码迷,mamicode.com
首页 > 数据库 > 详细

SQL Server在每个数据库上运行同一个脚本

时间:2021-01-19 12:01:00      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:upper   rop   create   sys   state   lda   table   port   dbn   

方法一:

Set NoCount On

if exists(select * from tempdb..sysobjects where id=object_id(‘tempdb..##tempEANReport‘))
Begin
drop table ##tempEANReport
End
Create Table ##tempEANReport
(
此处是临时表定义
)

declare @database_info table(id int identity, databasename varchar(100))

insert into @database_info
select name from sys.databases where name not in (‘master‘, ‘tempdb‘, ‘model‘, ‘msdb‘) and state = 0

declare @database_count int, @id int, @sql nvarchar(max), @Command nvarchar(max), @database_name varchar(100)

select @database_count = count(*) from @database_info

set @id=1

while @id<=@database_count
BEGIN

select @database_name = databasename from @database_info where id = @id

set @Command = ‘
insert into ##tempEANReport
SELECT ‘‘‘ + @database_name +‘‘‘ as [Database Name],
此处是sql脚本内容

set @sql = N‘USE [‘ + @database_name + ‘]
if (exists(select * FROM [‘ + @database_name + ‘].dbo.sysobjects WHERE id = OBJECT_ID(N‘‘‘ + @database_name + ‘.[dbo].[ct_costing_master]‘‘)))
begin ‘ +
@Command+
‘end‘

exec sp_executesql @sql
--PRINT @sql

set @id=@id+1

END
select * from ##tempEANReport

Drop table ##tempEANReport

Set NoCount OFF

 

方法二:

DECLARE @sTMCDatabaseName varchar(max)

DECLARE @sCheckIfSOLDatababase varchar(100)

DECLARE @SQL varchar(max)

DECLARE curForEachDB CURSOR LOCAL FOR
SELECT distinct db.name

FROM
sys.databases db
INNER JOIN sys.master_files mf
ON db.database_id = mf.database_id

WHERE
(
db.Name NOT IN (‘master‘, ‘model‘, ‘msdb‘, ‘tempdb‘)
And
substring(upper(db.name) ,1,9) <> ‘ASPSTATE_‘
)
AND
db.state = 0
OPEN curForEachDB
FETCH NEXT FROM curForEachDB INTO @sTMCDatabaseName
WHILE @@FETCH_STATUS = 0
BEGIN
--only execute when a SOL db.
SET @sCheckIfSOLDatababase = @sTMCDatabaseName + ‘.dbo.【tableName】‘

if object_id(@sCheckIfSOLDatababase) is not null
BEGIN
SET @SQL = ‘Use [‘ + @sTMCDatabaseName + ‘]‘ +
‘select ‘‘‘ + @sTMCDatabaseName + ‘‘‘ DBName, count(*)
此处是sql server脚本

EXEC (@SQL)
END
FETCH NEXT FROM curForEachDB INTO @sTMCDatabaseName
END

CLOSE curForEachDB
DEALLOCATE curForEachDB

SQL Server在每个数据库上运行同一个脚本

标签:upper   rop   create   sys   state   lda   table   port   dbn   

原文地址:https://www.cnblogs.com/samup/p/14292798.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!