Click here to Skip to main content
15,881,381 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
The background of the code: I wanted to have something which is collecting the used tables of the procedures, but my problem is that if the code reach a procedure which doesn't have any kind of reference it is crashed. How can I insert the procedures into the table with "N/A" value? I can solve it with Updates, but the main problem is that as I said that the "empty" procedures are killing the code running.

What I have tried:

<pre> DECLARE @SQL_Procedures NVARCHAR(MAX) = 
    (
    SELECT
    STRING_AGG(CAST( 
    'SELECT DISTINCT
    referenced_database_name AS [Database], 
    referenced_schema_name AS [Schema],
    referenced_entity_name AS [Table],'
    +rtrim(name)+' AS [Procedure]'+','+
    +'GETDATE() AS [Extract_Timestamp]'+
    ' FROM [INFO].[sys].[dm_sql_referenced_entities]''
    (' AS nvarchar(MAX))+QUOTENAME(schema_name(),'')+'.'+QUOTENAME(name,'') +N', ''OBJECT'')
    ', NCHAR(10) + N' UNION ALL ' + NCHAR(10)
    ) + NCHAR(10) + N'ORDER BY 1,2,3,4,5;'
     FROM dbo.sysobjects
     WHERE (type = 'P')
     AND name like 'p%'
     )
    
    PRINT(@SQL_Procedures)
    INSERT INTO [ABC].[dbo].[INFO_Procedures_Tables]
    EXEC sys.sp_executesql @SQL_Procedures 

Error message:


     <pre>...UNION ALL 
    SELECT DISTINCT
    referenced_database_name AS [Database], 
    referenced_schema_name AS [Schema],
    referenced_entity_name AS [Table],p_DET_INV_008 AS [Procedure],GETDATE() AS [Extract_Timestamp] FROM [I
    Msg 102, Level 15, State 1, Line 138
    Incorrect syntax near '
    ([dbo].[p_DET_INV_004], '.
Posted
Updated 16-Jan-21 1:59am
Comments
CHill60 15-Jan-21 11:03am    
Can you share what is produced from
PRINT(@SQL_Procedures)
- I don't have SQL 2017+ so can't run your code as it stands.

1 solution

Use Try/Catch, as in this example from TRY...CATCH (Transact-SQL) - SQL Server | Microsoft Docs[^]
BEGIN TRY  
     { sql_statement | statement_block }  
END TRY  
BEGIN CATCH  
     [ { sql_statement | statement_block } ]  
END CATCH  
[ ; ] 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900