Home > Articles > Programming > Windows Programming

Discovering Database Structure with VB .NET

When you build a database yourself, you know what you've put in it. But what do you do if you have a legacy database thrust upon you? How do you figure out what tables are present? What fields are in the tables? How are the tables related? This article explains some useful techniques for learning about the structure of an MSDE or SQL Server database using Visual Basic .NET.
Like this article? We recommend

Like this article? We recommend

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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020