TSQL - 动态更改数据库

时间:2017-03-16 17:50:53

标签: sql sql-server tsql

我在一家新公司工作,并试图编写一个循环数据库的proc,并在所有表,proc等中查找关键字。

它在理论上很有效,但是我注意到数据库永远不会改变。

我输出了SQL,然后运行它,没问题。但是,如果我运行这段代码,它就不会改变。

我还玩过代码并对表名进行了硬编码并使其工作,那么它是否可以作为安全功能?

这是TSQL:

Declare @Dbname varchar(250);   --Stores Database Name<br>
Declare @SearchTerm varchar(250); --What we're searching the DB for<br>
Declare @vSQL varchar(550)=''; --Variable that will hold our dynamic queries<br>
set @SearchTerm='LoadID';     <br>

select name 
from   sys.databases 
where  owner_sid != 0x01;

print @Dbname;
set @vSQL = 'use [' + @dbname + ']';
exec (@vSQL);

--exec @vSQL;
--execute (@vSQL);
--execute @vSQL);

2 个答案:

答案 0 :(得分:3)

EXEC在自己的环境中运行。将整个脚本放入@vSql类

set @vSQL = 'use [' + @dbname + '];' +'--do what you need ' ;

答案 1 :(得分:0)

我有的东西可以做到这一点,还有一点是以下过程。应循环遍历给定实例上的所有数据库,在这些数据库中的对象定义中查找关键字,以及任何作业是否使用这些对象及其上次执行持续时间。

USE [master]
GO

Create Proc dbo.DependencyCheck @SearchKey Varchar(150) As

Begin

--DB Refs

Drop Table If Exists #Databases

Create Table #Databases

(
    DatabaseName Varchar(50) Primary Key
    ,Checked Int Default 0 Not Null
    ,SearchKey Varchar(150)
    ,DependencyText As 'Insert Into #Dependencies 
                                            Select Distinct ' 

                                            + '''' + DatabaseName + '''' +  
                                            ',
                                            D.id As ObjectID,
                                            O.name As ObjectName,
                                            xtype As ObjectType,
                                            S.name As SchemaName

                                            From '

                                            + DatabaseName + '.dbo.syscomments D

                                            Inner Join ' + DatabaseName + '.dbo.sysobjects O
                                                On O.ID = D.id

                                            Inner Join ' + DatabaseName + '.sys.schemas As S
                                                On s.schema_id = O.uid

                                            Where D.text Like ''%' + SearchKey + '%'''
)


Insert Into #Databases (DatabaseName, SearchKey)

    Select 

    Name, @SearchKey

    From sys.sysdatabases As S 

    Where S.filename Not Like '%.SS' --Not DB Snapshots

Declare @TargetDatabase Varchar(25) = (Select Top 1 DatabaseName From #Databases As D Where D.Checked = 0)

--Dependency Table

Drop Table If Exists #Dependencies

Create Table #Dependencies

(
    DatabaseName Varchar(50) Not Null,
    ObjectID Int Not Null,
    ObjectName Varchar(150) Not Null,
    ObjectType Varchar(15) Not Null,
    SchamaName Varchar(150) Not null
)

--Dynamic SQL for Insert
Declare @DynamicDependency Varchar(8000) = (Select D.DependencyText From #Databases As D Where D.DatabaseName = @TargetDatabase)

While @TargetDatabase Is Not Null

    Begin 

        Exec(@DynamicDependency)

        Update D Set Checked = 1 From #Databases D Where DatabaseName = @TargetDatabase

        Set @TargetDatabase = (Select Top 1 DatabaseName From #Databases As D Where D.Checked = 0)
        Set @DynamicDependency = (Select D.DependencyText From #Databases As D Where D.DatabaseName = @TargetDatabase)

    End

;With JobStats As
(
Select Distinct

J.name,
JH.step_id,
First_Value(JH.run_duration) Over (Partition By J.name, JH.step_id Order By CA.StartTime Desc) As Last_Duration,
Avg(JH.run_duration) Over (Partition By J.name, JH.step_id) As Avg_Duration

From msdb.dbo.sysjobhistory As JH

Cross Apply (Select Convert(Datetime, Convert(varchar(8),run_date))
 + Convert(datetime, Stuff(STUFF(RIGHT(REPLICATE('0', 6) +  CAST(run_time as varchar(6)), 6), 3, 0, ':'), 6, 0, ':')) As StartTime) CA  

 Inner Join msdb.dbo.sysjobs As J
    On J.job_id = JH.job_id

Where JH.step_id <> 0
And JH.run_status = 1 -- Success 
)

Select 

D.ObjectID
,D.DatabaseName
,D.SchamaName
,D.ObjectName
,D.ObjectType
,J.name As JobName
,JS.step_id As JoBStepID
,JS.step_name As JobStepName 
,JStat.Last_Duration
,JStat.Avg_Duration

From #Dependencies As D 

Left Join msdb.dbo.sysjobsteps JS
    On JS.command Like '%' + D.ObjectName + '%'
    And JS.subsystem = 'TSQL'
Left Join msdb.dbo.sysjobs J
    On J.job_id = JS.job_id

Left Join JobStats JStat
    On JStat.name = J.name
    And JStat.step_id = JS.step_id

Order By 1, 3

End