我有很多视图和存储过程,我经常需要查看,为此,我将TSQL从SQL Server粘贴到Excel电子表格中,我可以在其中创建公式来分析它。
有没有办法(使用VBA?)将实际脚本从定义的视图或存储过程导入Excel中的单元格?
所以只是为了确认,我想返回脚本,而不是执行脚本的结果。
非常感谢
答案 0 :(得分: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'
for 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
答案 1 :(得分:1)
您可能还会发现exec sp_helptext对此有用,因为它会将输出拆分为单独的行而不是一列,这样可以更容易在Excel中查看。
exec sp_helptext "YourView/SP"
答案 2 :(得分:0)
通过检查sys.procedures
和sys.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'