In any given project, start with the experiment, set up a core design-time stored procedure, and use it to write the basic runtime stored procedure set of the database table. By creating and using these design-time processes, we not only save a lot of time, but also save money for our customers, plus some good code that we still use today.
These design-time stored procedures have been updated to take advantage of some of the new features of SQL Server 2000, particularly the user-defined function (UDFs) attribute. So the code becomes very modular, and we have additional functions to do other tasks.
Another benefit of design-time automation is to ensure that hundreds of stored procedures are generated with consistent structure and standard naming conventions. In our example, the name of all generated run-time stored procedures is formatted as: Prapp_tablename_task, where the Task can be Select, Update, or Delete. The stored procedures for the Customers and Orders tables are as follows:
Prapp_customers_delete
Prapp_customers_insert
Prapp_customers_select
Prapp_customers_update
Prapp_orders_delete
Prapp_orders_insert
Prapp_orders_select
Prapp_orders_update
As you can see, this specification adds a large number of organizations to the database so that any stored procedure is easily positioned and the name of each process is self-describing. Developers can quickly discover it and create code. Most importantly, future team members of this project will find the code and stored procedures easy to understand and use. Of course, if you've already used a different naming convention, simply change a few lines of code and your naming code can be replaced.
These four design-time stored procedures are not immutable, but can be used as templates in other projects. Install them into the project database and, if necessary, modify them to suit the needs of a particular application. For example, in several of our applications, we added code to maintain an audit record of each record being modified in a separate database.
A simple example
Before you begin, look at a simple example of using the Order_Details table in database Northwind (the table's table name is modified and the underscore replaces the space character). Although spaces and other characters are allowed in the object name, we recommend that you use the general delimiter to name objects to prevent problems that might arise when using these automated stored procedures, see the "Using Identifiers" section of the SQL Server online book for more information.
The first task is to run this design-time stored procedure to create a run-time stored procedure that modifies the Order_Details table data:
EXEC Pr__sys_makeupdaterecordproc ' Order_Details '
Running this design-time stored procedure produces the T-SQL script as shown in Figure 1. When this T-SQL script runs, it creates a new update stored procedure for the Order_Details table. All columns are described as parameters for the new stored procedure, but note how the primary key columns (OrderID and ProductID) appear in the WHERE clause when other non primary key fields are part of the SET Statement of the update command. The design-time stored procedures check the metadata (metadata) stored in the SQL Server system tables and use this information to create the appropriate output script, which will create the final run-time stored procedure (order_details).
The runtime produces only output and does not produce a new run-time stored procedure. However, with a simple modification, a design-time stored procedure can actually run a T-SQL script as the final output. To do this, we run only the design-time stored procedure, with a value of 1 as a flag bit, passed with a second selectable parameter, and run again:
EXEC pr__sys_makeupdaterecordproc ' Order_Details ', 1
This not only shows the previous output, but also runs the output, which creates the run-time stored procedure.
Now let's take a look at this code that creates a design-time stored procedure for a particular application run-time stored procedure.
SQL Server system tables and views
To create a design-time stored procedure, we must know how to obtain a table definition from the system tables and information views of SQL Server. First, we have to find these columns and find out which are the primary keys, what data types each column supports, and whether the columns are allowed to be empty.
Figure 2 View system tables
Learn that by modifying the properties of a registered server, SQL Server Enterprise Manager enables you to view system tables that are useful, as shown in Figure 2. If you right-click the server name in Enterprise Manager and choose Edit SQL Server Registration Properties, a dialog box pops up. Below the dialog box, you can see a check box labeled Show system Databases and system objects. Selecting this option opens the System object view, or it can be turned off to make the view of the table look simpler and easier to read.
Parsing table columns
The syscolumns table provides a number of required metadata information, such as column name, ID, length, and whether null values are allowed. It is also used to connect the sysindexes table to determine the primary key of the table. The same can be done through INFORMATION_SCHEMA. The COLUMNS view gets the default value for the column.
Since all stored procedures use the same metadata information, it is a good thing to encapsulate them in a separate block of code for modularity and maintainability reasons. Earlier versions of SQL Server did not have UDF (user-defined functions), making modularity look difficult. But SQL Server 2000 has the UDF feature, and we decided to take this code further and modularize the common features of the four design-time stored procedures. Create five new UDFs to handle system tables and information outline views, encapsulating all the obtained metadata.
There is no doubt that in order to create a new Run-time stored procedure, we need to know the following metadata column information about the table:
Column Name
The ID number of the column
Data type of column
Column maximum length (including character and binary data)
The precision of the column, or the number of digits of the value (decimal and numeric data)
The range of values for the column, or the number of digits after the decimal point (decimal and numeric data)
Whether the column is allowed to be null
Whether a column is part of a primary key
Whether the column is an Identity column
Default values for columns
Most of this information comes from syscolumns tables, except for two. The default value actually comes from INFORMATION_SCHEMA. COLUMNS view. The data type name (datatype name) is drawn from the systypes table and is combined with a more complex syscolumns,sysindexes and Sysindexkeys table to determine whether a column is part of a primary key. It's so complicated that we encapsulate that functionality into its own UDF.
Let's take a look at the main features in Figure 3, which reveal more meta data information. This UDF is not too complicated. As you can see, most metadata information--except for some simple rename naming--is returned without any modification, including column name, column ID, length, precision, range, whether null and data type names are allowed. Then you need to do a little extra work on this information. For primary key metadata, we have created another UDF to determine whether a column in a table is part of a table's primary key. We will examine these additional UDFs functions immediately.
Let's take a look at the alternate type and identity status. The 8th bit (128) of the Syscolumns status field indicates whether the column is an identity column. (This is important for knowing when to create Insert and Update scripts). Our simple formula enforces a logic and (&) on this value and wraps the result in the Sign function. If the bit is set, it means that the column is an identity column. C.status & 128 will return a value of 128. Otherwise, the value 0 is returned. The Sign function returns 1 when positive, and returns 0 when a negative number returns a value of -1,0. Therefore, if the column is evaluated as an identity column, the value 1 is returned, or 0 is returned.
The alternate type is used to indicate whether the data type requires additional information (length, precision, or range) when it is defined. We will character and binary data types as values are 1 alternate types, decimals and Numerics as 2, and other data types as 0. This value is used by the stored procedure to determine whether the length, precision, and scope need to be added to the parameter definition.
Find primary key columns
As you can see, it's not hard to find information about columns. It's a little bit more to find out if a field is part of a primary key. There is a list of fields that can be obtained. To find these fields, however, they can be found in the syscolumns, sysindexes, and Sysindexkeys table unions and are compared to the columns we requested (passed to the UDF in the @sColumnName parameters). Therefore, the task of finding the primary key is easier to complete in a separate user-defined function because we can encapsulate this work in a single function call.
Let's examine this function to see what happens:
CREATE FUNCTION Dbo.fniscolumnprimarykey
(@sTableName varchar (128), @sColumnName varchar (128))
RETURNS bit
As
BEGIN
DECLARE @nTableID int,
@nIndexID int,
@i int
SET @nTableID = object_id (@sTableName)
This function contains two parameters, table name and column name, and if the specified column is part of a primary key in the table, the function returns a bit flag. We then declare some of the variables to be used in the stored procedure and give the initial values. Now come to the interesting part: Find primary key information. We started to find the index ID for the primary key index of the table, as shown in the following code:
SELECT @nIndexID = indid
From sysindexes
WHERE id = @nTableID
and indid BETWEEN 1 and 254
and (status & 2048) = 2048
ORDER BY Indid
IF (@nIndexID is Null)
return 0
Now assign the index ID of the primary key index of this table to the variable @nIndexID. The 12th bit (2048) of the Status column indicates whether it is a primary key index. If it is not a primary key, no records are returned and the @nIndexID is set to a null value. Returns a value of 0 if @nindexid contains a null value when exiting the function. In other words, if there is no primary key index, then the column is not part of the primary key. Now we are again checking the required columns (@sColumnName) in the list of primary key indexed columns. IF @ColumnName in
(SELECT Sc.[name]
From Sysindexkeys Sik
INNER JOIN syscolumns sc on sik.id = sc.id and Sik.colid =
Sc.colid
WHERE sik.id = @nTableID
and Sik.indid = @nIndexID)
BEGIN
Original source from "Bit net", reprint please keep the original link: http://www.chinabyte.com/biz/cbfwq/347/2575347.shtml