2

我有很多视图和存储过程需要定期查看,为此,我将 SQL Server 中的 TSQL 粘贴到 Excel 电子表格中,我可以在其中创建公式来分析它。

有没有办法(使用 VBA?)将实际脚本从定义的视图或存储过程导入 Excel 中的单元格?

所以只是为了确认,我想返回脚本,而不是执行脚本的结果。

非常感谢

4

3 回答 3

1

从 SQL 的角度来看,您可以使用以下查询获取视图文本:

SELECT [definition]
FROM sys.sql_modules m 
INNER JOIN sys.objects o 
ON m.object_id=o.object_id
WHERE [name] = 'ViewName'
AND [type] = 'V'

对于 procs 将 WHERE 更改为:

WHERE [name] = 'Procname'
AND [Type] = 'P'

编辑:这是一个返回此数据的快速 VBA 函数,只需替换连接详细信息:

Public Function GetObject(ByVal nm As String, ByVal Tp As String) As String

    Set objMyConn = New ADODB.Connection
    Set objMyRecordset = New ADODB.Recordset
    Dim strSQL As String
    Dim retval As String

    With objMyConn
      .ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=[MyID];Password=[MyPass];Data Source=[ServerName];" & _
      "Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;" & _
      "Tag with column collation when possible=False;Initial Catalog=[DBName]"
      .Open
    End With

    strSQL = "SELECT [definition] " & _
    "FROM sys.sql_modules m " & _
    "INNER JOIN sys.objects o ON m.object_id=o.object_id " & _
    "WHERE [name] = '" & nm & _
    "' AND [Type] = '" & Tp & "'"


    Set objMyRecordset.ActiveConnection = objMyConn
    objMyRecordset.Open strSQL

    Do While Not objMyRecordset.EOF

        retval = objMyRecordset.Fields("description").Value

        objMyRecordset.MoveNext

    Loop

    Set GetObject = retval

End Function
于 2013-09-03T15:13:31.130 回答
1

您可能还会发现 exec sp_helptext 对此很有用,因为它将输出拆分为单独的行而不是一列,这可能会使在 excel 中查看更容易。

exec sp_helptext "YourView/SP"
于 2013-09-03T15:41:31.910 回答
0

您可以通过检查sys.proceduressys.sql_modules目录视图从 SQL Server 获取存储过程的“代码”(T-SQL 定义):

SELECT
    [pr].[name] ,
    [pr].[object_id] ,
    [pr].[type_desc] ,
    [pr].[create_date] ,
    [pr].[modify_date] ,
    [m].[definition] ,
    [m].[uses_ansi_nulls] ,
    [m].[uses_quoted_identifier] ,
    [m].[is_schema_bound] 
FROM sys.[procedures] pr
INNER JOIN sys.[sql_modules] m ON [pr].[object_id] = [m].[object_id]
WHERE pr.Name = 'whatever_stored_proc_name_you_want_to_analyze'

视图也是如此:

SELECT
    v.[name] ,
    v.[object_id] ,
    v.[type_desc] ,
    v.[create_date] ,
    v.[modify_date] ,
    [m].[definition] ,
    [m].[uses_ansi_nulls] ,
    [m].[uses_quoted_identifier] ,
    [m].[is_schema_bound] 
FROM sys.views v
INNER JOIN sys.[sql_modules] m ON v.[object_id] = [m].[object_id]
WHERE v.Name = 'whatever_view_you_want_to_analyze'
于 2013-09-03T15:13:00.090 回答