2

When I want to know if a stored procedure or views references a given name (table, view or column), I need a version of the object definition stripped of all comments.

Is this possible by a SQL query in an usual DBMS system?

Edit:

For SQL Server I found this solution using [Microsoft.Data.Schema.ScriptDom.Sql]. Here is the minimal PowerShell Code:

$sql = @'
select * from PowerShell -- a comment
where
 psRefnr = 1
'@
$options = new-object Microsoft.Data.Schema.ScriptDom.Sql.SqlScriptGeneratorOptions

$sr = new-Object System.IO.StringReader($sql)

$sg =     new-object Microsoft.Data.Schema.ScriptDom.Sql.Sql100ScriptGenerator($options)
$parser = new-object Microsoft.Data.Schema.ScriptDom.Sql.TSQL100parser($true)

$errors = $null
$fragment = $parser.Parse($sr,([ref]$errors))

$out = $null
$sg.GenerateScript($fragment,([ref]$out))

$out

The advantage of this approach is that it uses the official Microsoft parser.

3rd Edit:

The basic methods to get the procedure definitions in T-SQL are as mentioned [here][1] are

  1. sp_help proc_name
  2. SELECT [text] FROM sys.syscomments WHERE OBJECT_NAME(id) = 'proc_name'
  3. SELECT OBJECT_DEFINITION(OBJECT_ID('proc_name'))

The second and third option return columns of type varchar(max) which can be used in LIKE clauses.

Historical Note:

When '*=' and '=*' became obsolete, syscomments returned the definition in chunks of 255 characters and the two could be placed into different rows.

But the second problem isn't resolved yet. Some faltering developers tended to keep old code as C - style comments, making scanning for code containing deprecated syntax difficult.

Evan Carroll
  • 65,432
  • 50
  • 254
  • 507
bernd_k
  • 12,369
  • 24
  • 79
  • 111

2 Answers2

2

You could do this using T-SQL and various string functions, but you will need to account for comments using /**/ and --.

In other words, there is no easy way to get back a stored proc definition stripped of all comments. You would essentially need to build your own parsing tool.

SQLRockstar
  • 6,355
  • 27
  • 48
2

It is certainly possible to determine at the level of table or view in Oracle. Dependencies are tracked so that the relevant objects can be invalided when DDL changes occur.

Determining column level dependencies can be more difficult as the columns need to be matched to the appropriate table. Views can change column names, so the trace needs to be deeper.

Any false positives you get with comments left in probably indicates that the comments need to be fixed.

BillThor
  • 4,518
  • 20
  • 12