未加星标

Cleaning up Old Code and Unused objects in SQL Server

字体大小 | |
[数据库(mssql) 所属分类 数据库(mssql) | 发布者 店小二04 | 时间 2019 | 作者 红领巾 ] 0人收藏点击收藏

In this article, we are going to talk about discovering and archiving SQL references to invalid procedures.

We have a significant amount of database code within our database procedures we no longer use, as we’ve changed objects referenced in procedures. As we’ve moved to source control for all of our databases, we’re seeing the costs of keeping old code in our environment that we no longer use. The trouble is that we don’t know how to identify what we use since we have many teams who develop objects in our databases and use them for the features they create. What are some techniques for cleaning old database code on the database level as well as preventing this problem in the future?

Overview

Outside of the storage costs and repository costs where we must sync with many objects, old database code in the form of stored procedures that we no longer use raises security risks, as procedures provide access to data through CRUD operations. If we don’t use database code, we should practice eliminating it immediately. It is a major security risk to have stored procedures that are no longer used. As for functions, this depends on the function in question, but I recommend the practice of only keeping what’s required. We can apply the same lessons to views, users, roles, etc as well the more database objects we use, the more we need to restrict or eliminate as we change our environment.

For the best practice to reduce effort, if we replace a database object with another object (such as replacing an old procedure with a new procedure), we should remove the old object immediately. We can archive the old object for SQL reference in an archive source control location, but we should never keep the object live. This best practice will prevent a database from possessing objects that are no longer used but could possibly reveal inappropriate information to a malicious actor.

Demonstration with A Stored Procedure

In the below code, we create a table that we’ll use for an experiment. Once we create the table, we create a procedure that inserts a record from a parameter the procedure accepts into our newly created table. We then test the procedure a few times, query the table, then drop the table. Now, when we execute the stored procedure, we get an error the procedure fails. As we see in the below code, we can remove a table that’s referenced in a procedure.

--- Window 1 CREATE TABLE DataEntry( TextId TINYINT IDENTITY(1,1), TextEntry VARCHAR(9) ) --- Window 2 CREATE PROCEDURE addDataEntry @string VARCHAR(9) AS BEGIN INSERT INTO Dataentry (TextEntry) VALUES (@string) END EXEC addDataEntry 'ref-1' EXEC addDataEntry 'ref-2' EXEC addDataEntry 'ref-3' EXEC addDataEntry 'ref-4' EXEC addDataEntry 'ref-5' SELECT * FROM DataEntry DROP TABLE DataEntry EXEC addDataEntry 'ref-6'
Cleaning up Old Code and Unused objects in SQL Server

Our query shows the results of the data we added.


Cleaning up Old Code and Unused objects in SQL Server

We can remove the table, but now when we call the procedure, the procedure fails since the table doesn’t exist.

This may be one of the complexities that we’re solving for: an invalid SQL reference where an object refers to another object that no longer exists. This scenario could also be a procedure calling another procedure with the second procedure not existing.

Identifying SQL References Before a Drop

One clear solution here is to identify all references prior to dropping the referenced object and the same applies if we rename the object. Using the above example of removing a table, we could look for all the references to the table we’re dropping in our procedures, views, etc. This code becomes invalid if they reference the removed object and removing them with it reduces possible errors. There may be cases where we want to update the reference if we’ve renamed the object or created a new object to replace the old one. The flow of removing an object should be to identify references first and include these references as objects to be removed if we need to remove an object. The below diagram shows this.


Cleaning up Old Code and Unused objects in SQL Server

Using the above image as an example, if we remove the referenced table, notice the impact it would cause on all the other references to the table they would be invalid.

The same logic applies to other changes from renaming objects to changing data types to changing primary keys (which should be extremely rare, but unfortunately happen). These changes can have significant effects on code that reference these. We must account for all dependent code which will be affected prior to making the change.

Assuming that we use source control for our database from database objects to application code we can iterate over our files using PowerShell and obtain SQL references. We’ll want to use searches that reflect how we name objects; notice the nuances in the below select statements for one table all of which return the same data set, but query the table differently:

SELECT * FROM etlMidLoader SELECT * FROM dbo.etlMidLoader SELECT * FROM [dbo].etlMidLoader SELECT * FROM [dbo].[etlMidLoader] SELECT etlMidLoader.* FROM [dbo].[etlMidLoader] SELECT [etlMidLoader].* FROM [dbo].[etlMidLoader]

Developers sometimes name tables the same name as column names, so searching for a table name may return results you don’t want to see, such as returning a column from a table you don’t want to remove or update. I tend to develop with the approach of restricting most object names (tables, views, procedures, etc) with a starting identifier either indicating the object type or purpose (tb or etl) or using the action it performs (helpful for views or procedures) and the reason is that searches through source control become fast as I never get a column and table clash. One of the best DBAs I worked with enforced this rule by removing any object that didn’t follow appropriate naming convention immediately without warning it made developers create objects with the right name from the beginning and saved time when tracking down dependencies (this also saved a lot of time for other tracking purposes). However, this assumption would be inappropriate in many development environments because many environments don’t have strict practices like this.

In the below code, we look for the object etload in our source control by filtering on SQL files exclusively (our assumption here being that we’re using SQL for references) and we return the file name plus the line of the file we found it along with the line of text. This script is not procedure-biased either unless we only point it at a directory that holds procedures (relative to design); it will search all SQL files for references. Even comments should be reviewed, as it’s a common practice by developers to use multi-line comments. Relative to how specific we want our filter, we can edit the if statement in the below code to be very specific with regular expressions.

Function Read-ForSpecificText { Param( [Parameter(Mandatory=$true)][string]$file , [Parameter(Mandatory=$true)][string]$objectpattern ) Process { $readfile = New-Object System.IO.StreamReader($file) $identifylineno = 0 while (($fileline = $readfile.ReadLine()) -ne $null) { if ($fileline -match “$objectpattern”) { Write-Output (‘”’ + $file + ‘” ‘ + $identifylineno.ToString() + “: “ + $fileline) } $identifylineno++ } $readfile.Close() $readfile.Dispose() } } $sourcecodesql = Get-ChildItem “C:\Src\Repo One\Reposins\” -Filter *.sql -Recurse foreach ($sqlfile in $sourcecodesql) { Read-ForSpecificTe

本文数据库(mssql)相关术语:熊片数据库 mssql数据库 oracle数据库 pubmed数据库 access数据库 万方数据库

代码区博客精选文章
分页:12
转载请注明
本文标题:Cleaning up Old Code and Unused objects in SQL Server
本站链接:https://www.codesec.net/view/627880.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 数据库(mssql) | 评论(0) | 阅读(93)