简体   繁体   中英

Running a system Stored Procedure of SQL Server using python pyodbc

I am trying to run a system SP (which is a pre-built) using python pyodbc . In fact I am trying to see the dependencies on a table using sp_depends '<Object name>';

I am using the below code snippet.

df_f=[]
l_table = ['table_1','table_2','table_3']
try:
  for l in l_table:
    sql = """EXEC sp_depends '{0}';""".format(l)
    while cur.nextset():
        cur.execute(sql)
        c = cur.fetchall()
        df_l= pd.DataFrame.from_records(c, columns = [desc[0] for desc in cur.description])
        df_l['Referenced_Object'] = l
        df_f.append(df_l)
        break
except pyodbc.Error as err:
  s = str(err)
  print(s)
finally:
  cur.close()
  cnxn.close()

The above code is not running. It is not throwing error but not appending anything in df_f .

If I run the above SP separately, I am getting the below error:

ProgrammingError: No results.  Previous SQL was not a query.

I have taken help from this SO thread.

I am not able to SET NOCOUNT ON in this SP as this is a built-in and therefore I am not able to get the desired information in dataframe.

Any clue on this?

As I mentioned in the comments, sp_depends has been deprecated; it should not be used. As per the documentation you should be using sys.dm_sql_referencing_entities and sys.dm_sql_referenced_entities instead.

You can get similar results to the sp_depends with the following queries. You would need to replace the variables with parameters from your programming language ( not inject them):

SELECT CONCAT(re.referenced_schema_name,'.', re.referenced_entity_name) AS [name],
       o.type_desc AS [Type],
       CASE re.is_updated WHEN 0 THEN 'no' WHEN 1 THEN 'yes' END AS updated,
       CASE re.is_selected WHEN 0 THEN 'no' WHEN 1 THEN 'yes' END AS selected,
       re.referenced_minor_name AS [column]
FROM sys.dm_sql_referenced_entities(QUOTENAME(@SchemaName) + N'.' + QUOTENAME(@ObjectName) ,'OBJECT') re
     JOIN sys.objects o ON re.referenced_id = o.object_id;

SELECT DISTINCT
       CONCAT(re.referencing_schema_name,'.', re.referencing_entity_name) AS [name],
       o.type_desc AS [Type]
FROM sys.dm_sql_referencing_entities(QUOTENAME(@SchemaName) + N'.' + QUOTENAME(@ObjectName) ,'OBJECT') re
     JOIN sys.objects o ON re.referencing_id = o.object_id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM