Discovering Database Structure with VB .NET
- Exploring the Server
- Learning About Tables
- Learning About Fields
- An Example
- Conclusion
If you're an experienced ADO programmer, you probably know that you can find out what fields a table contains by executing a SQL SELECT command and then examining the results. For example, the following statement selects all of the fields in the Customers table. After you execute it, you can look through the results to get the names of the fields.
SELECT * FROM Customers
That's fine as far as it goes but an MSDE or SQL Server database can contain a lot of other important information. This technique doesn't tell you which fields are required, which have associated validation routines, which are related to fields in other tables as foreign keys, or which must have unique values.
Fortunately, SQL Server databases provide an overabundance of stored procedures that return information about the server and about the database. This article describes some of the more useful of those procedures.
Notes
Note that this only works for SQL Server and MSDE databases (MSDE is a restricted set of SQL Server. See my article, "Getting Started with MSDE and VB .NET," for information about MSDE databases). They won't work for Access, Oracle, Informix, or other databases. Oracle and other high-end databases may contain their own stored procedures for performing similar chores, however.
After you know what the stored procedures described here do, you'll need a way to execute them. You can easily write a Visual Basic .NET application that executes the procedures, examines the results, and takes whatever action is necessary. For example, a program might build an SqlConnection object, attach it to a database, and then use the sp_tables stored procedure to list the tables in the database. Processing the results is a bit outside the scope of this article, however.
My article, "Executing Ad Hoc Queries with VB .NET," shows how to build a program that can execute any SQL statement and display the returned values. You can use that program to run these stored procedures and examine the results. See that article for more details and to download the program.
The last section in this article also shows you how to make a program that uses the stored procedures to study the basic structure of a database. You can use that program as a starting point for your own.
Test Database
The examples shown in this article use a small quiz score database named TestScores. The database contains two tables, Students and TestScores, which were created using the following SQL script:
# Students. CREATE TABLE Students ( StudentId INT IDENTITY(1,1) PRIMARY KEY, FirstName VARCHAR(20) NOT NULL, LastName VARCHAR(20) NOT NULL, CONSTRAINT con_Students_Names UNIQUE (FirstName, LastName) ); # Scores. CREATE TABLE TestScores ( StudentId INT REFERENCES Students (StudentId), TestNumber INT NOT NULL, Score INT NOT NULL CHECK ((Score >= 0) AND (Score <= 100)), CONSTRAINT pk_TestScores PRIMARY KEY (StudentId, TestNumber) );
This script contains several interesting bits of database code including a UNIQUE constraint on the FirstName/LastName combination in the Students table, a CHECK constraint in the TestScores table, a two-field primary key in the TestScores table, and a foreign key in the TestScores table (the StudentId field references the Students table's StudentId field). Using SQL Server's stored procedures, a VB .NET application can learn about all of these things.
The following sections describe stored procedures that return information about the database at three different levels: server, database, and table.
Exploring the Server
In SQL Server, a server contains one or more databases. Usually, you need to work with a particular database, but you may need to find out what databases the server contains. You may also need to learn about the server itself. The following subsections describe some of the more useful server-level stored procedures.
sp_server_info
The sp_server_info stored procedure lists information about a server. The stored procedure returns a series of records with three fields: attribute_id, attribute_name, and attribute_value. The results include such values as the database management system's name (Microsoft SQL Server) and version, and whether the database supports save points and named transactions.
sp_helpserver
The sp_helpserver stored procedure returns a single record giving additional information about the server. The following table shows the values returned during one database session. Your program probably knows the name of the server to which it is connected, but the name and network_name fields may be useful if you don't have that information handy. For example, if you are building a small subsystem, it may be easier to fetch this information yourself than it would be to ask other developers to modify the part of the application that connects to the database.
Field Name |
Value |
name |
BENDER\NetSDK |
network_name |
BENDER\NetSDK |
status |
rpc,rpc out,use remote collation |
id |
0 |
collation_name |
NULL |
connect_timeout |
0 |
query_timeout |
0 |
sp_who
The sp_who stored procedure returns information about the users and processes connected to the server. The following text shows some typical output. Most of the entries describe automatic database system processes. The program that generated this output is listed second-to-last. When the stored procedure ran, the program was connected to the OrderEntry database, and it was running a SELECT statement (as part of the stored procedure).
All of the processes in this output were logged in as sa (system administrator). If your database contains separate IDs for each user, the loginname field will be much more useful.
spid ecid status loginame hostname blk dbname cmd ==== ==== =============== ======== ======== ===== ========== ================ 1 0 background sa 0 NULL LAZY WRITER 2 0 sleeping sa 0 NULL LOG WRITER 3 0 background sa 0 master SIGNAL HANDLER 4 0 background sa 0 NULL LOCK MONITOR 5 0 background sa 0 master TASK MANAGER 6 0 background sa 0 master TASK MANAGER 7 0 sleeping sa 0 NULL CHECKPOINT SLEEP 8 0 background sa 0 master TASK MANAGER 9 0 background sa 0 master TASK MANAGER 10 0 background sa 0 master TASK MANAGER 11 0 background sa 0 master TASK MANAGER 51 0 runnable sa BENDER 0 OrderEntry SELECT 52 0 sleeping sa BENDER 0 master AWAITING COMMAND
sp_databases
The sp_databases stored procedure lists the databases available on a server. The following text shows the results of this statement on my database book's test server. Some of these, including master, are SQL Server system databases. For example, the master database contains the system stored procedures and other system information.
DATABASE_NAME DATABASE_SIZE REMARKS =============== ============= ======= Contacts 3072 NULL Customers 3072 NULL master 12480 NULL model 1152 NULL msdb 13312 NULL MultiUserOrders 3072 NULL Numbers 3072 NULL OrderEntry 3072 NULL Orders 3072 NULL tempdb 8704 NULL TestAccounts 3072 NULL TestRoles 3072 NULL TestScores 3072 NULL TestSecurity 3072 NULL TestViews 3072 NULL Trans 3072 NULL
sp_helpdb
The sp_helpdb stored procedure returns additional information about the server's databases. The following text shows the results returned for my book's test server. The status field has been truncated because it is very long for some databases.
name db_size owner dbid created status compatibility_level =============== ============= ===== ==== =========== ================== =================== Contacts 3.00 MB sa 7 Jan 3 2002 NULL 80 Customers 3.00 MB sa 13 Dec 12 2001 NULL 80 master 12.19 MB sa 1 Aug 6 2000 Status=ONLINE, ... 80 model 1.13 MB sa 3 Aug 6 2000 Status=ONLINE, ... 80 msdb 13.00 MB sa 4 Aug 6 2000 Status=ONLINE, ... 80 MultiUserOrders 3.00 MB sa 16 Jan 12 2002 NULL 80 Numbers 3.00 MB sa 9 Dec 5 2001 NULL 80 OrderEntry 3.00 MB sa 5 Nov 5 2001 Status=ONLINE, ... 80 Orders 3.00 MB sa 15 Jan 9 2002 NULL 80 tempdb 8.50 MB sa 2 Jan 16 2002 Status=ONLINE, ... 80 TestAccounts 3.00 MB sa 8 Dec 3 2001 NULL 80 TestRoles 3.00 MB sa 10 Dec 7 2001 Status=ONLINE, ... 80 TestScores 3.00 MB sa 6 Nov 7 2001 Status=ONLINE, ... 80 TestSecurity 3.00 MB sa 11 Dec 7 2001 Status=ONLINE, ... 80 TestViews 3.00 MB sa 12 Dec 7 2001 Status=ONLINE, ... 80 Trans 3.00 MB sa 14 Dec 28 2001 Status=ONLINE, ... 80