0% found this document useful (0 votes)
4 views

Beginning SQL Server 2000 for Visual Basic Developers 1st Edition Thearon Willis (Auth.) instant download

The document is a promotional overview of the book 'Beginning SQL Server 2000 for Visual Basic Developers' by Thearon Willis, which covers various aspects of SQL Server 2000, including installation, database design, security, and stored procedures. It includes links to download the book in various formats and mentions other related titles by the author. Additionally, it provides a detailed table of contents outlining the chapters and topics covered in the book.

Uploaded by

hemkerwebiw
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Beginning SQL Server 2000 for Visual Basic Developers 1st Edition Thearon Willis (Auth.) instant download

The document is a promotional overview of the book 'Beginning SQL Server 2000 for Visual Basic Developers' by Thearon Willis, which covers various aspects of SQL Server 2000, including installation, database design, security, and stored procedures. It includes links to download the book in various formats and mentions other related titles by the author. Additionally, it provides a detailed table of contents outlining the chapters and topics covered in the book.

Uploaded by

hemkerwebiw
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

Beginning SQL Server 2000 for Visual Basic

Developers 1st Edition Thearon Willis (Auth.)


pdf download

https://ebookgate.com/product/beginning-sql-server-2000-for-
visual-basic-developers-1st-edition-thearon-willis-auth/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Beginning Microsoft Visual Basic 2008 Thearon Willis

https://ebookgate.com/product/beginning-microsoft-visual-
basic-2008-thearon-willis/

ebookgate.com

Beginning SQL Server for Developers Fourth Edition Robin


Dewson

https://ebookgate.com/product/beginning-sql-server-for-developers-
fourth-edition-robin-dewson/

ebookgate.com

Murach s SQL Server 2012 for Developers 1st Edition Bryan


Syverson

https://ebookgate.com/product/murach-s-sql-server-2012-for-
developers-1st-edition-bryan-syverson/

ebookgate.com

Beginning Microsoft SQL Server 2008 Programming Robert


Vieira

https://ebookgate.com/product/beginning-microsoft-sql-
server-2008-programming-robert-vieira/

ebookgate.com
SQL Server 2000 Stored Procedures Handbook 1st Edition
Tony Bain

https://ebookgate.com/product/sql-server-2000-stored-procedures-
handbook-1st-edition-tony-bain/

ebookgate.com

Pro ASP NET for SQL Server High Performance Data Access
for Web Developers 1st Edition Brennan Stehling

https://ebookgate.com/product/pro-asp-net-for-sql-server-high-
performance-data-access-for-web-developers-1st-edition-brennan-
stehling/
ebookgate.com

Beginning Visual Basic Net Databases 1st Edition Denise


Gosnell

https://ebookgate.com/product/beginning-visual-basic-net-
databases-1st-edition-denise-gosnell/

ebookgate.com

SQL Server T SQL Recipes 4th Edition Jason Brimhall

https://ebookgate.com/product/sql-server-t-sql-recipes-4th-edition-
jason-brimhall/

ebookgate.com

Beginning jQuery 2 for ASP NET Developers 1st Edition


Bipin Joshi

https://ebookgate.com/product/beginning-jquery-2-for-asp-net-
developers-1st-edition-bipin-joshi/

ebookgate.com
Summary of Contents
Introduction
Chapter 1: Introduction to SOL Server 2000
Chapter 2: Installing the Personal Edition of SOL Server 2000
Chapter 3: Designing and Creating the Development Database
Chapter 4: SOL Server Security
Chapter 5: SWl Server Ouery Analyzer
Chapter 6: Database Connections
Chapter 7: Introduction to Stored Procedures
Chapter 8: Stored Procedures versus SOL Statements
Chapter 9: Selecting Data
Chapter 10: Inserting Data
Chapter 11: Updating Data
Chapter 12: Deleting Data
Chapter 13: Working with Text Data
Chapter 14: Installing Internet Information Server (liS)
Chapter 15: SOL Server and XMl
Chapter 16: XMl Web Reports
Case Study: Part 1- Building an English Ouery Application
Case Study: Part 2- Deploying an English Ouery Application
Appendix A: SOL Server and VB Data Types
Appendix B: ADO 2.6 Object Model
Appendix C: SOL Server Functions
Appendix D: Building the Hardware Tracking Framework
Appendix E: Creating the Hardware Tracking Business Server Component
Appendix F: References
Appendix G: Support, Errata, support.apress.com
Index
Beginning SQL Server 2000 for
Visual Basic Developers

Thearon Willis

APress Media, LLC


Beginning SQL Server 2000 for Visual Basic Developers

Copyright © 2003 by Thearon Willis


Originally published by Apress in 2003
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopying, recording, or by any information storage
or retrieval system, without the prior written permission of the copyright owner and the publisher.
ISBN 978-1-59059-273-1 ISBN 978-1-4302-5131-6 (eBook)
DOI 10.1007/978-1-4302-5131-6

Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit
of the trademark owner, with no intention of infringement of the trademark.

Distributed to the book trade in the United States by Springer-Verlag New York, Inc., 175 Fifth
Avenue, New York, NY, 10010 and outside the United States by Springer-Verlag GmbH & Co. KG,
Tiergartenstr. 17,69112 Heidelberg, Germany.

In the United States: phone I-BOO-SPRINGER, email orders@springer-ny.com. or visit


http://www.springer-ny.com. Outside the United States: fax +49 6221 345229, email
orders@springer.de, or visit http://www.springer.de.

For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219,
Berkeley, CA 94710. Phone 510-549-5930, fax 510-549-5939, email info@apress.com, or visit
http://www.apress.com.

The information in this book is distributed on an "as is" basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author{s) nor Apress shall have
any liability to any person or entity with respect to any loss or damage caused or alleged to be caused
directly or indirectly by the information contained in this work.

The source code for this book is available to readers at http://www.apress.comin the Downloads
section.
Credits

Editorial Board Technical Reviewers


Dan Appleman Robin Dewson
Craig Berry N athen Grass
Gary Cornell Ian Herbert
Tony Davis Jim Ley
Steven Rycroft Frank Miller
Julian Skinner Narender Mutyyala
Martin Streicher John Roth
Jim Sumser Pamela Smith
Karen Watterson Richard Ward
Gavin Wray
John Zukowski Production Coordinators
Mark Burdett
Project Manager Laurent Lafon
Cilmara Lion
Jake Manning Additional Layout
Tom Bartlett
Index Pippa W onson
Adrian Axinte Laurent Lafon

Cover Figures
Kurt Krames Shabnam Hussain

Managing Editor Technical Editors


Bruce Lawson Ewan Buckingham
Dominic Lowe Ben Egan
Gary Evans
Proofreader Dianne Parker
Chris Smith
About the Author
Thearon began his career in computers in 1980 as a computer operator. During the fall of 1980 he
took a course in BASIC programming using the Radio Shack TSR-80 computer and has been hooked
on programming ever since.

After learning the BASIC language Thearon moved on to learn COBOL and began writing programs
to help automate some of his daily tasks as a computer operator. Advancing his career, Thearon
became an Operations Analyst and learned several other languages to assist in his job.

In 1989 Thearon moved into Systems Programming and started programming in S370 ASSEMBLER
language. He coded batch programs in ASSEMBLER language and then moved on to code CICS
programs. The Help Desk and Network Operations used these batch and online programs to perform
some of their daily tasks, such as monitoring CICS printers and polling sales. During this time he
started working with relational databases on the mainframe and immediately saw the benefits that
relational databases provided.

Between the years of 1988 and 1993 Thearon learned several more programming languages, which
include QBASIC, PASCAL, and C++. Thearon decided that he enjoyed programming so much that
he switched his career path and became a developer full time.

The first application that Thearon worked on was written in ASSEMBLER language and included
over 70 ASSEMBLER programs. To help automate some of the tasks that were performed by the
department that used this application, he wrote several programs in Visual Basic. One of these
programs read and processed data from message queues that were populated from the mainframe,
and performed automated balancing.

Thearon first began working with Visual Basic in version 3.0. After version 4 was released he
switched his career from the mainframe to client-server development. He still enjoys working with
relational databases and uses SQL Server as the back-end to all of his applications that store and
retrieve data.

Thearon currently works as a senior consultant and develops intranet/Internet and business-to-
business applications. He lives with his wife Margie and daughter Stephanie in Charlotte, North
Carolina.

I would like to thank some ofthe folks at Wrox Press for making this book possible. Thanks go to
Dominic Lowe for getting this project started, to Dianne Parker for her invaluable insight and technical
editing skills, to Ben Egan for his hard work, and to Cilmara Lion for coordinating the work.

I would like to thank my wife Margie for her faith in me and the patience she has shown while I
write one book after another. It is to her and my daughter Stephanie that I dedicate this book.
Beginning SQL Server 2000 for Visual Basic Developers

Copyright © 2003 by Thearon Willis


Originally published by Apress in 2003
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any
means, electronic or mechanical, including photocopying, recording, or by any information storage
or retrieval system, without the prior written permission of the copyright owner and the publisher.
ISBN 978-1-59059-273-1 ISBN 978-1-4302-5131-6 (eBook)
DOl 10.1007/978-1-4302-5131-6

Trademarked names may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit
of the trademark owner, with no intention of infringement of the trademark.

For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219,
Berkeley, CA 94710. Phone 510-549-5930, fax 510-549-5939, email info@apress.com, or visit
http://www.apress.com.

The information in this book is distributed on an "as is" basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author{s) nor Apress shall have
any liability to any person or entity with respect to any loss or damage caused or alleged to be caused
directly or indirectly by the information contained in this work.

The source code for this book is available to readers at http://www.apress.comin the Downloads
section.
Table of Contents

Introduction 1
What This Book Is About 1
How This Book Is Organized 2
Who This Book Is For 5
What You Need To Use This Book 5
Conventions 6
Downloading The Source Code 7
TeU Us What You Think 7
Errata & Updates 8

Chapter 1: Introduction to SQL Server 2000 11

SQL Server 2000 11


SQL Server Instances 12

SQL Server Databases 12


Database Files 13
Transaction Logs 15
Tables 16
Primary Keys, Foreign Keys, and Referential Integrity 17
Indexes 19
Defaults 21
Stored Procedures 21
Triggers 22
Views 23

OLE DB, ODBC, and ADO 23


XML 25
English Query 26
Analysis Services 26
Meta Data Services 27
DTS 27
Summary 28
Table of Contents

Chapter 2: Installing the Personal Edition of SOL Server 2000 31


SQL Server Editions and Platforms 32
Enterprise Edition 32
Developer Edition 32
Personal Edition 33
Standard Edition 33
Desktop Engine 34
Windows CE Edition 34
SQL Server Prerequisites 34
Installation 35
SQL Server Instances 35
Installation Procedure 36
Server Components 42
Management Tools 43
Client Connectivity 43
Books Online 43
Development Tools 43
Code Samples 44
Installing Additional Instances 49
Installation Wrap-Up 49

Tools Overview 50
Enterprise Manager 50
Databases 52
Data Transformation Services 53
Management 54
Replication 55
Security 56
Support Services 57
Meta Data Services 57
Query Analyzer 58
SQL Server Profiler 59

Wizards 60
Register SQL Server Wizard 60
Create Database Wizard 60
Create Index Wizard 61
Create Login Wizard 61
Full-Text Indexing Wizard 61
Wizard Summary 61

Summary 62

Chapter 3: Designing and Creating the Development Database 65


Project Scope 66
Relational Database Design 67
Normalization 69
First Normal Form 69
Second Normal Form 70
Third Normal Form 72

ii
Table of Contents

Suggested Naming Conventions 72


Identifying Objects 72
Tables 73
Columns 73
Primary and Foreign Keys 74
Indexes 74
Views 74
Triggers 74
Stored Procedures 74
Creating Tables 82
Creating Foreign Key Constraints 88
Additional Indexes 96

Summary 99

Chapter 4: SOL Server Security 101


General Security Overview 102
Authentication 103
Windows Authentication 103
Password Expiration 103
Account Lockout 103
Auditing 104
User Groups 104
SQL Server Authentication 104
Roles 104
Server Roles 105
Database Roles 106
User-Defined Database Roles 107
Creating Logins 111
Database Security 122
Object Security 123
Table Security 123
Column Security 123
View Security 123
Stored Procedure Security 124
Summary 124

Chapter 5: SOL Server Ouery Analyzer 127


Query Analyzer Overview 127
Starting and Connecting 128
Menus 130
File Menu 130
Edit Menu 131
Query Menu 132
Tools Menu 133
Window Menu 134
Help Menu 134
Toolbar 135
Selecting a Database 136

iii
Table of Contents

Object Browser 136


Query Analyzer Color Coding Scheme 138
Saving Queries and Query Results 139
Update and Delete Statements 147
Update Statement 148
Delete Statement 152
Debugging 153
Templates 156
Summary 163

Chapter 6: Database Connections 167


Connections 168
ADO Object Model 168
ADO Objects and Collections 170
Properties Collection 170
Connection Object 170
Command Object 170
Recordset Object 170
Record Object 171
Stream Object 171

Connection Object 171


ODBC versus OLE DB 172
Setting Up a DSN 173
Creating the Login Form 181
DSN Connections 186
SQL Server Authentication 186
Windows Authentication 192
DSN Connections Summary 193
DSN·less Connections 193
DSN-Iess Connections Summary 197
Which Connection Method to Use 197
Summary 198

Chapter 7: Introduction to Stored Procedures 201


Stored Procedure Basics 202
Stored Procedure versus Transact-SQL Performance 202
User Prefixes and Security 203
Create Procedure Syntax 205

iv
Table of Contents

Select Stored Procedures 205


Using the Recordset Object to Return Results 209
Stored Procedure Parameters 218
Insert Stored Procedures 221
Update Stored Procedures 226
Delete Stored Procedures 232
Stored Procedure Summary 235
Recordset Methods 237
Saving and Opening a Recordset 245

Summary 249

Chapter 8: Stored Procedures versus SOL Statements 253


Side-by-Side Comparisons 254
Select Comparison 254
Select Comparison Summary 266
Insert Comparison 266
Insert Comparison Summary 276
Update Comparison 276
Update Comparison Summary 286

Optimizing In-Line SQL Statements 287


Summary 292

Chapter 9: Selecting Data 295


Table Preparation 296
Joins 299
Inner Join 300
Cross Join 301
Left Outer Join 301
Right Outer Join 301
Full Outer Join 302

Temporary Tables 330


Table and Column Aliases 333
Summary 351

Chapter 10: Inserting Data 353


Local Variables 353
Conditional Processing Logic 356
Error Handling in SQL Server 371
Summary 399

V
Table of Contents

Chapter 11: Updating Data 403


COM+ versus SQL Server Transactions 404
SQL Server Transactions 404
Using SQL Server Transactions 405
Granting Permissions Through Code 410
Stored Procedure Data Validation 425
Editing a Stored Procedure 437
Summary 447

Chapter 12: Deleting Data 451


Referential Integrity 451
Cascading Referential Integrity Constraints 452
Triggers 455
Viewing Triggers 460
Viewing Constraints 476
Summary 482

Chapter 13: Working with Text Data 485


How SQL Server Manages Text Data 485
Setting the Text In Row Option 487
Creating a Notes Table 488
Altering a Table 489
Inserting Text Data 491
Selecting Text Data 494
Text Pointers 510
Reading Text Data 512
Updating Text Data 518
Writing Text Data 526
Reminders 535
Summary 535

Chapter 14: Installing Internet Information Server (liS) 539


115 Overview 539
Requirements 540
115 Installation for Windows 2000 540
115 Installation for Windows NT 4.0 544
Creating a Virtual Directory for a Web Site 550
Creating a Virtual Directory for SQL Server 554
Summary 560

vi
Table of Contents

Chapter 15: SQL Server and XML 563


XML Overview 564
Selecting XML Data 566
Selecting XML Data in a URL 569
XSL Stylesheets 571
Sorting Data Using XSL 577
Using XSL Templates 577

Calling Stored Procedures in URLs 584


Stored Procedure Parameters 585
XML Templates 592
XML Templates that Accept Parameters 595
XML Template Summary 597
Annotated XDR Schemas 597
Summary 602

Chapter 16: XML Web Reports 605


More XSL Elements 606
XSL Scripts 606
Evaluating Data - Making Decisions 607
Using the test Attribute 607
Using the expr Attribute 608

Creating Web Reports 609


Dynamic HTML 626
Web Report with Hidden Details 627

Organizing Your SELECT Statement 637


The <xsl:for-each> Element 652
Summary 660

Case Study Part 1: Building an English Query Application 663


English Query Installation 663
English Query Overview 667
English Query and Visual InterDev Integration 669
Creating an English Query Application 670
Summary 709

vii
Table of Contents

Case Study Part 2: Deploying an English Ouery Application 713


Web Deployment Methods 713
Distributing the Run-Time Engine 714
Setting Up 715
Building the Web Pages 715
Using VB for Deployment 747
Summary 748

Appendix A: SOL Server and VB Data Types 751

Appendix B: ADO 2.6 Object Model 755


Objects 755
Command Object 756
Methods 756
Properties 756
Connection Object 757
Methods 757
Properties 758
Error Object 759
Properties 759
Errors Collection 759
Methods 759
Properties 759
Field Object 760
Methods 760
Properties 760
Fields Collection 761
Methods 761
Properties 761
Property Object 761
Properties 761
Properties Collection 762
Methods 762
Properties 762
Parameter Object 762
Methods 762
Properties 762
Parameters Collection 763
Methods 763
Properties 763
Record Object 764
Methods 764
Properties 764
Recordset Object 765
Methods 765
Properties 766
Stream Object 768
Methods 768
Properties 769

viii
Table of Contents

Appendix C: SOL Server Functions 771


String Functions 771
System Functions 780
Date and Time Functions 793
Aggregate Functions 796

Appendix D: Building the Hardware Tracking Framework 803

Appendix E: Creating the Hardware Tracking Business Server Component 819


Removing the Classes 819
Creating the Component 820
Front-end Modifications 828
Summary 829

Appendix F: References 831

SQL Server References 831


XML References 831
Other Technologies 832

Appendix G: Support. Errata. and forums.apress.com 835

Support and Errata on www.apress.com 836


Finding Errata 836
Adding an Erratum to the Web Site 836
Customer Support 836
What We Can't Answer 836
How to Tell Us Exactly What You Think 836

The Peer-to-Peer Forums at forums.apress.com 837

Index 845

ix
Introduction

Everywhere you look these days Microsoft SQL Server is there. You hear about dotcom companies
running SQL Server and accessing terabytes of data, and applications that need to be scaled up from
Access to use SQL Server. You just can't seem to escape the presence of SQL Server in the workplace.

SQL Server 2000 is the latest release and, because of performance enhancements and new features, this
is a great time to learn how to use SQL Server and how to incorporate it into your applications.

Whether you are building VB applications (front-end or back-end) or web applications, if you need data
access to SQL Server 2000 this book can help. While most of the book covers accessing SQL Server
2000 from VB, the same principles can be applied to Active Server Pages using VBScript and ADO
(Active X Data Objects). This book covers the use of in-line SQL statements and stored procedures, and
how to use both in your VB programs and web applications.

The new XML features of SQL Server 2000 are also covered - you will learn how to execute queries
and stored procedures in the URL of a web browser to retrieve XML data from the database. XML
templates, XSL stylesheets, and XML schemas are also covered, and we show you how to format your
XML data into a presentable format for display in a browser.

SQL Server 2000 includes many useful tools. For example, English Query is a powerful tool for building
applications that allow users to access the data without understanding query languages or the structure
of the database. This book will step you through creating your own English Query application.

What This Book Is About


This book will introduce you to SQL Server 2000, starting with the basic concepts and working through
the features that are most commonly used by VB developers. We start by introducing the core
components of a SQL Server database, such as tables, primary keys and foreign keys, indexes, and
stored procedures.

We cover the installation of the Personal Edition of SQL Server 2000 and show you how to install
multiple instances of SQL Server 2000 on the same machine. We then move on and discuss relational
database design, and help you get off on the right foot by walking through the design and normalization
of the development database that will be used throughout this book.
Introduction

We discuss SQL Server security and show you how to grant access to the various database objects to
users and roles that we set up. We also cover database connections and how to create DSN and DSN-
less connections from VB using both Windows authentication and SQL Server authentication.

One whole chapter has been set aside to cover the details of the Query Analyzer. This is a powerful tool
that you as a developer will use to write and debug queries and stored procedures. This tool also allows
you to view and manage the objects in your database, such as tables and stored procedures.

Creating and using stored procedures is covered in depth and we walk you through building a sample
application that uses stored procedures to select, insert, update, and delete data. As you progress from
one chapter to the next you will be building upon the previous chapter's content to increase the
functionality of the sample application. By the time you get to the end of the book, not only will you
have gained a better understanding of SQL Server and stored procedures, but you will also have a
complete application that serves as an example for future reference and use.

The last chapters in this book deal with the XML features of SQL Server 2000. The first of these gets
you up to speed with XML and covers some simple formatting of XML data using XSL stylesheets. The
second walks you through the process of creating XML reports that are displayed in a web browser.

The case study, split into two parts, introduces you to English Query and shows you how to build and
deploy an English Query application. English Query is a separate product that ships with SQL Server
2000 - it allows you to build an application that your end users can use to ask natural English questions
to query the database. These questions are translated into SQL statements behind the scenes and are
executed, returning the data that the user has asked for.

How This Book Is Organized


This section provides a summary of each chapter, showing how we start with the basics and work our
way up to more complex topics.

Chapter 1 - Introduction to SQL Server 2000


This chapter covers an overview of SQL Server 2000 and all of the objects that make up a database. We
cover databases, transaction logs, tables, indexes, and constraints. We also introduce you to data access
with ADO, XML support in SQL Server 2000, English Query, and Analysis Services.

Chapter 2 - Installing the Personal Edition of SQL Server 2000


This chapter covers the various SQL Server 2000 editions and the prerequisites for installing the
Personal Edition of SQL Server 2000. After covering the installation of the Personal Edition we
introduce you to the various tools that are installed with SQL Server, including the Enterprise Manager.

Chapter 3 - Designing and Creating the Development Database


This chapter covers relational database design and will walk you through the design and normalization
of the development database that will be used throughout the rest of the book. We also cover some
suggested naming standards that can be used. We create, step-by-step, the development database and
show you how to view and modify the database.

2
Introduction

Chapter 4 - SQL Server Security


This chapter covers the two types of security modes in SQL Server: Windows authentication and SQL
Server authentication. We show you how to use both, and we will continue to do so as we progress
through the book. Database security is also covered and, after we discuss how this works, we show you
how to grant permissions on the database objects that you create.

Chapter 5 - SQL Server Query Analyzer


This chapter introduces you to the features of the Query Analyzer. You get first hand experience with
this powerful tool as we walk through its features and learn how to use them. The Object Browser is
covered in depth as you learn how to view and manipulate the objects in your database and discover
how to use this feature to your benefit.

Chapter 6 - Database Connections


This chapter covers connecting to SQL Server from your VB program using both DSN and DSN-Iess
connections with Windows authentication and SQL Server authentication. We build a login form that
gives you a choice of which mode and type of connection to use. We also show you how to create a
DSN to be used in a DSN connection.

Chapter 7 - Introduction to Stored Procedures


This chapter begins your introduction to stored procedures as we cover stored procedure input and
output parameters and return values. We walk through simple examples showing you how to build these
stored procedures as well as call them from your VB programs. This chapter includes a look at some
useful methods of the ADO Recordset object, to retrieve multiple results sets and to work more
efficiently with static data.

Chapter 8 - Stored Procedures versus SQL Statements


Having had an introduction to stored procedures, this chapter shows a side-by-side comparison of using
stored procedures and in-line SQL statements in VB. You will come to realize what can and cannot be
accomplished using in-line SQL statements, and also the power and flexibility that stored procedures
provide. Ways of optimizing in-line SQL statements are also demonstrated.

Chapter 9 - Selecting Data


This chapter covers creating stored procedures that select data. We cover simple SELECT statements
and then progress to more complex SELECT statements that use joins. The various types of joins are
discussed and used in our stored procedures. This chapter introduces the Hardware Tracking
application that will be expanded on in the following chapters.

Chapter 10 - Inserting Data


INSERT stored procedures are covered in this chapter and we introduce topics such as conditional
processing logic and error handling in your stored procedures. The stored procedures start to become
more complex at this stage and these stored procedures are incorporated into the Hardware Tracking
application.

Chapter 11 - Updating Data


This chapter covers UPDATE stored procedures and shows you how to use logic in your stored
procedures to validate data if needed. We also introduce transactional processing in stored procedures,
allowing you to create stored procedures that use transactions.

3
Introduction

Chapter 12 - Deleting Data


This chapter not only covers stored procedures that delete data but it also covers triggers. We will walk
you through the process of creating triggers that can be used to delete data. Along with this we also
cover cascading referential integrity constraints. We show you exactly how they work and also show you
how to create and use them.

Chapter 13 - Working with Text Data


This chapter shows you how to work with text data in SQL Server 2000. This chapter covers more
advanced topics regarding SQL Server data types and processing, as well as ADO. We use the
GetChunk and AppendChunk methods in ADO to manage large amounts of data. We show you how
text data is managed in SQL Server and how to work with it efficiently. This chapter completes the
Hardware Tracking application that is written in VB.

Chapter 14 - Installing Internet Information Services (liS)


This chapter helps you prepare for the next chapter and for the case study by walking you through the
process of installing liS and setting up a virtual directory that will be used for your intranet web site.
We also walk through the steps to set up a virtual directory for SQL Server that will allow us to query
the database directly from the URL of a web browser.

Chapter 15 - SQL Server and XML


This chapter introduces you to the XML features of SQL Server 2000. We explore how to query the
database through the URL of the web browser using both SQL statements and stored procedures. We
also cover XML templates, XSL style sheets, and XML schemas. We display raw XML data in the
browser and, through the use of XSL style sheets, display formatted XML data in the browser.

Chapter 16 - XML Web Reports


This chapter continues your study of XML by showing you how to create XML reports that are
displayed in the browser. We take a more in-depth look at XML templates and XSL stylesheets to create
sophisticated web reports. We cover the use of scripts in both XSL and HTML to format, display, and
manipulate data.

Case Study part 1 - Building an English Query Application


This part of the case study introduces you to English Query and walks you through the steps of
installing it. We then proceed to build an English Query application using our development database as
the source. We learn how to use entities and relationships effectively to build a powerful application for
our users.

Case Study part 2 - Deploying an English Query Application


The second part of the case study shows you how to deploy your completed English Query application
over the web. We walk through the steps of creating the web pages that will host your English Query
application. When we are done, you will have deployed your English Query application over the
intranet.

Appendix A - SQL Server and VB Data Types

Appendix B - ADO 2.6 Object Model

4
Introduction

Appendix C - SQL Server Functions

Appendix D - Building the Hardware Tracking Framework

Appendix E - Creating the Hardware Tracking Business Server Component

Appendix F - References

Appendix G - Support, Errata, and forums.apress.com

Who This Book Is For


Since this is an Apress Beginning series book, it is our goal to teach you everything you need to know to
get up to speed using SQL Server 2000 from the ground up. This book is aimed at experienced Visual
Basic developers who want to increase their knowledge and skill set by using an enterprise relational
database.

Although experienced VB developers with little or no knowledge of databases should be able to learn
all of the basics needed, there are two types of VB developers for whom this book is ideal:

o Experienced developers who are making the transition from Access to SQL Server 2000
o Experienced developers who are making the transition from some other type of enterprise
relational database, such as Oracle or Sybase

This book assumes you are an experienced Visual Basic developer and as such will not teach you how
to code Visual Basic, but instead will teach you how to create SQL Server stored procedures and call
them from your Visual Basic programs and web pages.

A basic understanding of relational database concepts will be helpful but is not assumed, as this topic is
covered in the first few chapters of this book. It is also not assumed that you have any experience
working with ADO, but again it will be an advantage if you have.

What You Need To Use This Book


You will need a copy of SQL Server 2000 to install the Personal Edition on your workstation. Your
workstation can be Windows 98, Windows NT 4.0, or Windows 2000 (Professional or Server). If you
cannot get a copy of SQL Server 2000 to install on your workstation, you can use an edition of SQL
Server 2000 (Standard or Enterprise) installed on your network. If you will be using a network-installed
edition of SQL Server 2000, consult with your database administrator about creating the sample
database for you, and have them grant you database administrator rights to that database.

Since this book is about learning how to use SQL Server 2000, we will step you through installing the
Personal Edition on your workstation.

5
Introduction

You will need Visual Basic 6.0 installed in order to develop and try the examples in this book. You will
also need the Windows NT 4.0 Option Pack if your workstation is running Windows 98 or Windows NT
4.0, in order to tryout the web-based examples.

All code and samples in this book were developed and tested on workstations running Windows 2000
Professional and Server editions.

Conventions
To help you understand what's going on, and in order to maintain consistency, we've used a number of
conventions throughout the book:

When we introduce new terms, we highlight them.

These boxes hold important information.

Advice, hints, and background information comes in an indented, italicized font like this.

Try It Out

After learning something new, we'll have a Try It Out section, which will demonstrate the concepts
learned, and get you working with the technology.

How It Works
After a Try It Out section, there will sometimes be a further explanation, to help you relate what you've
done to what you've just learned.

Words that appear on the screen in menus like the File or Window menu are in a similar font to what
you see on screen. URLs like http://www.apress.com are also displayed in this font.

Keys that you press on the keyboard, like etrl and Enter, are in italics.

We use two font styles for code. If it's a word that we're talking about in the text, for example, when
discussing functionNames (), <Elements>, and obj ects, it will be in a fixed pitch font. If it's a
block of code that you can type in and run, or part of such a block, then it's also in a gray box:

<html>
<head>
<title>Simple Example</title>
</head>
<body>
<p>Very simple HTML . </p>
</body>
</html>

6
Introduction

Sometimes you'll see code in a mixture of styles, like this:

<html>
<head>
<title>Simple Example</title>
</head>
<body>
<p>Very simple HTML.</p>
</body>
</html>

In this case, we want you to consider the code with the gray background, for example to modify it. The
code with a white background is code we've already looked at, and that we don't wish to examine
further.

Downloading The Source Code


As we move through the chapters there will be copious amounts of code available for you, so that you
can see exactly how it works. We'll also be stopping frequently and trying it out, so that you can not
only see how things work, but make them work yourself.

The source code for all of the examples is available for download - more on that in a while. You might
decide that you prefer to type all the code in by hand. Many readers prefer this because it's a good way
to get familiar with the coding techniques that are being used.

Whether you want to type the code in or not, we have made all the source code for this book available
at our web site, in the Downloads section at the following address:

http://www.apress.com

If you're one of those readers who likes to type in the code, you can use our files to check the results
you should be getting - they should be your first stop if you think you might have typed in an error. If
you're one of those readers who doesn't like typing, then downloading the source code from our web
site is a must!

Either way, it'll help you with updates and debugging.

Tell Us What You Think


We've worked hard to make this book as relevant and useful as possible, so we'd like to get a feel for
what it is you want and need to know, and what you think about how we've presented things.

If you have anything to say, let us know at:

http://www.apress.com

7
Introduction

Errata Be Updates
We've made every effort to make sure there are no errors in the text or the code. However, to err is
human, and as such we recognize the need to keep you informed of any mistakes as they're spotted and
amended.

More details on finding out about errata and providing us with feedback can be found in Appendix G.

8
Introduction to SQL Server 2000

SQL Server 2000 is the latest release of SQL Server and it brings about a lot of changes to the user
interface, as well as performance enhancements in the underlying database engine. If you are new to
SQL Server this product will amaze you with its richness of features and ease of use. If you are
upgrading from a previous version of Sm. Server you will find that SQL Server 2000 has many new
features to offer developers.

This chapter focuses on the core concepts and features of SQL Server 2000 from a developer's
standpoint. We will discuss the basic concepts of databases in SQL Server 2000 and some of the
additional features that SQL Server 2000 has to offer.

In this chapter we will introduce:

o SQL Server 2000


o SQL Server databases and database objects
o OLE DB, ODBC, and ADO
o XML
o English Query
o Analysis Services, Meta Data Services, and DTS

SQL Server 2000


Most people think of SQL Server as solely a relational database. However, SQL Server 2000 is actually
a family of separate, but inter-related product components - these include the Relational Datahase
Engine, Replication, Data Transformation Services (DTS), Analysis Services, Meta Data Services, and
English Query. We will discuss these in a little more detail later in this chapter.

The Relational Database Engine is at the heart of SQL Server and provides the majority of the services
that we will be dealing with in this book. The database engine is highly scaleable - it can perform
optimally on a single computer running the Windows 2000 Professional operating system, or can be
scaled up to function on a cluster of servers running Windows 2000 Datacenter Server. We will cover all
of the operating systems that SQL Server 2000 can run on in the next chapter.
Chapter 1

The database engine can also dynamically tune itself. That is, it can acquire and release system
resources as the need arises. For example, if the system is running with 50 concurrent users and 50 more
users log onto the system, SQL Server will automatically acquire the resources necessary. Likewise, if
your transaction log fills up and you have it set to automatically grow, SQL Server will allocate it more
space so the database will keep running. We will discuss transaction logs in more detail later in this
chapter.

Not only does SQL Server provide the database engine, but it also provides many robust user interfaces.
Among these are the Enterprise Manager, which allows us to perform administrative tasks on SQL
Server databases, and the Query Analyzer, a most useful tool for developers. The latter assists the
developer in writing and debugging queries and stored procedures. We will cover both of these user
interfaces in more depth in later chapters, as well as learning what queries and stored procedures are.

As we progress through this and the next several chapters you will come to realize what a powerful
database application SQL Server 2000 is, with easy-to-use interfaces and many powerful features.

SQL Server Instances


SQL Server 2000 introduces a new feature called named instances. An instance is just an installation of
SQL Server 2000, whether it is the first installation on a machine or a subsequent installation on the
same machine. The first installation of SQL Server 2000 on a machine, with no previous versions
installed, is considered the default instance. This operates and is addressed like previous versions of
SQL Server. For example, the default instance of SQL Server 2000 installed on a computer named
SProd1 would be addressed as SProd1.

The named instance feature allows you to install SQL Server 2000 on a computer already running a
previous version of SQL Server or a default instance of SQL Server 2000. Each additional instance of
SQL Server 2000 installed on the same machine must be given a unique instance name. These names
are limited to 16 characters and are not case sensitive. So if we install a second instance of SQL Server
2000 on SProd1 and give it an instance name Client1 then we would address that instance of SQL
Server as SProd1 \Client1.

Each instance of SQL Server is isolated from the rest. This means that if, for example, your organization
were a service provider, you could install multiple instances of SQL Server 2000 on the same machine
and install additional service packs without affecting the settings of the other copies. The only shared
components between instances are the tools, search services, and the English Query application. Put
simply, everything that is installed in the Microsoft SQL Server program group (for example the
Enterprise Manager, Query Analyzer, and Books Online) is shared between instances and everything
else is isolated. Clients can connect to any instance of SQL Server on a Single machine, providing they
have the correct access permissions.

We will explore named instances in more depth in the next chapter when we actually walk through the
procedure for installing SQL Server 2000.

SQL Server Databases


SQL Server 2000 consists of many databases. Indeed, it even uses databases to store information about
itself! Each database consists of multiple objects, with the database itself also considered an object.

12
Introduction to SQL Server 2000

The objects contained in each database are as follows:

0 Tables
0 Keys
0 Indexes
0 Constraints
0 Stored procedures
0 Views
0 Triggers
0 Defaults
0 User-defined functions
0 User-defined data types
0 Users
0 Roles
0 Rules

We will cover these objects in this and subsequent chapters.

As we mentioned earlier, SQL Server provides a tool known as the Enterprise Manager - this allows us
to manage all of the databases created in SQL Server from one window. The Enterprise Manager is the
main user interface to SQL Server and allows us to view and manipulate the various objects in our
databases. Using the Enterprise Manager, we can connect to other SQL Servers installed on the network
and administer them all from the same window, as long as we have the appropriate permissions. We will
be covering the Enterprise Manager in the next chapter after we have installed SQL Server.

The user who creates a database is considered the owner of that database. Only that user and the
database administrator will initially have access to the database. (The database administrator is usually
defined as the person or persons who have access to the system administrator login, sa.) This is part of
the security features of SQL Server; all objects are secure until the appropriate permissions are granted.
Chapter 4 will discuss SQL Server security in greater detail and demonstrate how to grant permissions
on various database objects to other users. The database owner or the database administrator must
explicitly grant permissions on the database to other users before they can access or work with the
database. Once this is done the other users can then create objects in the database, such as tables, stored
procedures, and views, depending on the permissions they have been granted.

Database Files
A SQL Server database is organized into logical objects that are visible to the user, such as tables,
indexes, and stored procedures. Behind the scenes a Sm. Server database is actually implemented as
two or more physical files on the file system. The first file is the data file and contains all of the
information that makes up a SQL Server database. The second file is called a transaction log file and
contains the transaction logs, which are records of changes made to the database. Transaction logs will
be covered in more detail in the next section.

A primary data file is the first data file created when you create your database. Primary data files for a
database are created with the . mdf file extension by default. You can change this, but it is not
recommended for the sake of consistency. As your database grows and you run out of room on the hard

13
Chapter 1

drive in which the primary data file was placed you can create one or more secondary data files. These
are usually created with the . ndf file extension by default. Again, you can use whatever file extension
you want but to be consistent with others you should use the default. It also helps to maintain
consistency within your SQL Server installation and aids the quick identification of database files.
Creating secondary files on different drives of your computer will spread the workload of your database
across other drives and thus improve the performance of your database.

Log files are used to hold all of the information needed to recover your database, either from a system
failure or from accidental or purposeful destruction of data. These log files are kept separate from the
data files so that, although they may reside on the same physical volume, they are never created in the
same physical file. Log files are created with the default extension of . Idf and, again, you should not
change this. Wherever possible your log files should be created on separate physical drives to protect
against drive failure.

You can create SQL Server data and log files on either FAT or NTFS file systems. You cannot,
however, create a data or log file on a compressed volume in these file systems. FAT stands for File
Allocation Table and is a file system that has been around since DOS. Windows 95/98 and, optionally,
Windows NT12000 use the FAT file system. NTFS is an acronym for NT File System and is used
exclusively by Windows NT12000. This file system provides security and recovery features not available
in the FAT file system.

The following diagram shows the implementation of the logical database that you see into the physical
database that SQL Server uses. The logical database is the database that you see in the Enterprise
Manager and the physical database is the group of files that make up the database on your hard drive.
Database A contains a primary data file that has been populated to capacity, meaning there is no more
space available in this file. Therefore a second data file was created for this database with a file
extension of . ndf, indicating that it is a secondary database file. Each database in the diagram has its
own transaction log file, which is used to record the transactions that occur in the database. Database B
in the diagram only contains a primary data file and a transaction log file:

" ~-=~~~=='-~~~ =1l


i Stored Procedures Stored Procedures ii
' Triggers Triggers : I
Views Views : I
-~.----.------.--.--- .. -. -. -------_.---_. ----.---------------.-----
SQL Server (DBMS)

,,. ------- . -- -------------------------------,,,,


, ,.-
t- --
~ t:: --
~

. Database A
Data 1
Database A
Data 2
I Database B
Data
.mdf .ndf .mdf

l
Database A
Log
.Idf
Database B
Data
.Idf
:
:
II
'

: :-------------------------------------------: ------------ -----_ .... ------~ ~

14
Introduction to SQL Server 2000

SQL Server as the database management system (DBMS) actually resides in the middle, as shown in the
diagram, managing the physical implementation of the database in the file system and also the logical
database that users interact with. It uses various programs to manage the physical database files, such as
the relational database engine and the storage engine. It also uses various programs to manage the
lOgical database, such as the Enterprise Manager and the Query Analyzer.

As a developer you shouldn't be too concerned with the physical implementation of the database files
but it helps to understand the big picture. An understanding of what goes on behind the scenes is useful
when you need to design databases and communicate with the database administrator. However, what
you are really concerned with is the logical implementation of the database, such as tables, keys, and
indexes. These are the things that you can control to optimize the way your database performs. For
clarity, the objects listed at the top of the diagram represent only a partial list of the objects that make
up a database.

Chapter 3 will help you to better understand how databases are implemented in SQL Server, as we step
through creating our own development database.

Transaction Logs
As we mentioned above, each database that you create has its own transaction log. The transaction log
contains details of transactions that have been applied against your database. A transaction is the
execution of a group of SQL statements as one logical unit of work.

SQL is an acronym for Structured Query Language. Any application that accesses SQL Server does so
through the use of SQL statements, which perform such actions as selecting data, and creating and
modifying the structure of your database.

SQL Server automatically manages transactions within the transaction log and will record a "before and
after" picture of the data in a table that has changed. This means that if you execute an update query to
revise a row of data, SQL Server will log a record of the data before and after it was changed. This
allows for both backward and forward recovery of the data in your database, should the need arise.

o A forward recovery means that if you have a hardware failure, you can restore your database
from the last backup, and then apply the transaction logs to recover the transactions from the
point of the last backup.
o A backward recovery means that if your stored procedure or business component implements
transactions, and somewhere in the processing your code decides that it needs to back out of
those transactions, the transaction log will be used to recover the data to the state the data was
in before the changes began.

SQL Server manages transaction logging automatically. You can, however, use transactions in your
queries and stored procedures to perform automatic recovery of the data that you changed. Transactions
will be covered in depth in Chapter 11 where we will show you how they work and also how to
implement them in your stored procedures.

Incremental backups of your transaction logs should be performed on a regular basis, and the database
administrator normally handles these. Incremental backups can be used to recover transactions that
were processed since the last time your database was backed up. This is useful when you need to restore
and recover your database after a hardware failure. Performing incremental backups also serves to clear
the transaction log file, making room for new transactions.

15
Chapter 1

You can truncate the transaction log to remove old records that are no longer needed. SQL Server will
automatically truncate the transaction log when a backup of the log is performed. It also automatically
truncates the file when a checkpoint is processed and the Truncate Log On Checkpoint option is turned
on for the database. With this option turned on you could potentially lose transaction records if the log
is truncated without first backing it up.

A checkpoint is used to minimize the amount of data in the transaction log that must be processed to
recover the database. When a checkpoint of the log is taken, it writes unsaved changes to disk, making
them a permanent part of the database. SQL Server will store as many transactions in memory as it can
before writing them to disk - this is just one way that SQL Server optimizes performance. When this
process is completed, the pages of the transaction log are free to be used by new transactions. SQL
Server automatically performs checkpoints on the log and uses the blocks that have been freed up. A
checkpoint is automatically performed, based on the number of records in the log and not based on the
time since the last checkpoint.

Tables
Databases contain many different types of objects but the table is perhaps the most fundamental of
these. A table is an object in your database that contains information. You could create a table that
contained data about employees and this table would represent information about each employee in
your organization. Each table that you define is made up of columns and rows. Each column represents
an attribute about the information that is stored in your table, such as an employee's title and first or last
name. Collectively, the columns form a row in your table that represents a single occurrence of the
information that the table represents, which in this case is a single employee.

The following partial table is taken from the Employees table in the sample Northwind database that
is installed with SQL Server. Notice how each column represents an attribute of the employee being
defined and each row represents a single employee:

Column 1 Column 2 Column 3 Column 4


EmployeeID LastName FirstName Title

Rowl Davolio Nancy Sales Representative

Row 2 2 Fuller Andrew Vice President, Sales

Row 3 3 Leverling Janet Sales Representative

Each database in SQL Server contains a collection of tables. These include multiple system tables. SQL
Server creates these system tables when we initially create a database and they are used to manage
information about the database. As users we create one or more user tables that contain the information
that we want to store in the database, such as products and suppliers. These tables contain data that is
related in some way, such as a supplier who supplies parts to manufacture a product. This is part of
what makes up a relational database - the relationship of objects. We'll be discussing the concept of
relational database design in more detail in Chapter 3.

A table can contain up to 1,024 columns but it is highly unlikely that we would have that many
columns. We usually normalize our database and end up with more tables and fewer columns.
Normalization is the process of eliminating duplicate data and providing a fast efficient search path to
the data, which will also be covered in detail in Chapter 3.

16
Introduction to SQL Server 2000

Each column in a table must have a unique name within that table, but you can use the same column
name in multiple tables. Along the same lines, each table in a database must have a unique name but,
again, you can have the same table name in different databases.

As we mentioned earlier, each table you create is secure and no other user can access it until you grant
them permission. There are different levels of permissions that can be granted on a table to each user or
role. A role is assigned a unique name, and defines a group of users who have the same permissions.
You can, for example, allow one group of users to select data, while allowing another user to both select
and insert data, by placing them in different roles. Object level permissions and roles will be discussed
in detail in Chapter 4 when we look at SQL Server security.

Each table in a database can contain one or more objects, such as constraints, triggers, or defaults.
These objects help to preserve and enforce data integrity within your tables. Data integrity ensures
that each column in a table contains the correct data values. These topics will be covered later in
this chapter.

Each table in a database usually has a special column, called an identity column, which uniquely identifies
each row of data. Generally, this column contains a sequential number that is automatically incremented
by SQL Server, although other values are possible, as will be discussed in more detail in Chapter 3.

Identity columns are typically used in SQL Server to assign a unique number to each row in a table,
which will ensure the uniqueness of that row's data. This column is also typically used as the primary
key column, although it can alternatively be used in the index. We will be discussing primary keys and
indexes next.

Primary Keys, Foreign Keys, and Referential Integrity


A primary key identifies the column or columns whose values uniquely identify a row of data in the table. No
two rows in a table can contain the same primary key and SQL Server enforces this rule. This is why primary
key columns are often defined using an identity column, where each row has a unique value automatically
generated for it. Primary keys may also contain other non-numeric values, such as an employee's employee
number, which could consist of alphabetic and numeric characters. Also, primary key columns cannot
contain null values. A null value is one that is missing, in other words the data does not exist.

When a primary key is created on a table, SQL Server automatically creates a unique index for the
primary key on the table. This ensures that no two primary keys can be the same. Indexes are covered in
more detail in the next section. For now it is enough to know that using an index on the primary key
column provides a fast, efficient path to the data when the primary key is used for data access.

If a primary key consists of data from multiple columns, the individual columns can contain duplicate
values but, when taken as a whole, the reference must be unique. In other words, if a primary key
consists of data from column A and column B, column B can contain duplicate values or column A can
contain duplicate values. However, the combination of columns A and B must be unique within each
row of the table.

Foreign keys are keys that point to the primary key in another table. A foreign key in one row of a table
points to an exact row of data in another table. A foreign key value cannot be inserted into a table if the
row of data that it is pointing to in another table does not exist. This is just one of the constraints that
are placed on foreign keys which help to ensure referential integrity.

17
Chapter 1

Consider the following diagram as an example. We can have more than one employee sharing the same
title, so we have moved the Ti tle column into a separate table. This reduces the amount of duplicate
data, and then the two tables are joined using a foreign key. The following figure shows how the foreign
key, Ti tleID, in the Employees table, points to the primary key in the other table. This approach
provides more efficient storage of the data, as we need only store a foreign key pointing to one row of
data in the Title table.

This example also demonstrates referential integrity; suppose we had not inserted the second row of
data in the Ti tle table. The foreign key constraint would not allow us to insert a value of 2 in the
Ti tleID column of the Employee table for the second employee.

Primary Key Foreign Key

1
EmployeelD LastName FlrstName
1.
TltlelD
Employees table 1 Davolio Nancy 1-
2 Fuller Andrew 2 -~

3 Leverling Janet 1- ~ r-

Primary Key

1
TltlelD Title
Title table 1 Sales Representative
2 Vice President, Sales

Referential integrity enforces the defined relationship of data between tables, and is automatically
applied to foreign keys. Just as we cannot insert a foreign key value for a row of data that does not exist
in another table, referential integrity prevents us from deleting a row of data that is referenced by a
foreign key. In order to delete a row of data that is referenced by a foreign key, we must first delete the
row of data containing the foreign key or update the column using a null value. Then we are able to
delete the row containing the primary key.

Referential integrity is based on the relationship between foreign and primary keys and it ensures that
key values are consistent across all tables. Referential integrity is automatically enforced by SQL Server,
and prevents a user from updating a primary or foreign key that would break the integrity of the data.
Also, as we mentioned earlier, SQL Server prevents you from inserting a foreign key that does not
reference a valid primary key, and additionally prevents you from deleting a primary key that is being
referenced by a foreign key.

Cascading Referential Integrity Constraints


Cascading referential integrity constraints is a feature of SQL Server 2000 that allows you to decide what
action, if any, SQL Server should take when a user updates or deletes data that is referenced by a foreign
key in another table. There are two cascading constraints available: ON UPDATE and ON DELETE.

18
Introduction to SQL Server 2000

The ON UPDATE cascading constraint specifies what action should be taken on the foreign keys that
reference the primary key in the table when the primary key is updated. NO ACTION, which is the default
when this constraint is not specified, will cause SQL Server to take no action. In this case an error is
raised when a user tries to update the primary key column that is referenced as foreign keys in other
tables. CASCADE specifies that an update to the primary key should be cascaded to all foreign keys that
reference this primary key.

Let's look at an example of ON UPDATE CASCADE and use the tables shown in the previous figure.
Suppose we updated the value for the column Ti tleID from 1 to 100 in the Ti tle table. This change
would then be cascaded to the Employees table and all employees who had a TitleID of 1 would
now have a Ti tleID of 100, as shown in the following figure:

Primary Key Foreign Key

•I
EmployeelO
...I
LastName FlrstName TltlelO
-
Employees table 1 Davolio Nancy 100-
2 Fuller Andrew 2 -
3 leverling Janet 100- r-

Primary Key

1
Title table
TltlelO
100
Title
Sales Representative I
2 Vice President, Sa les

Cascading updates are useful in situations where the primary key requires changing.

The ON DELETE cascading constraint specifies what action should be taken on the foreign keys that
reference the primary key in the table when the primary key is deleted. Again, NO ACTION is the default,
and will cause SQL Server to take no action. Just as with ON UPDATE, an error is raised when a user
tries to delete the primary key column that is referenced as foreign keys in other tables. CASCADE
specifies that the deletion of the primary key should be cascaded to all foreign keys that reference this
primary key. In other words, all rows that have foreign key references to the primary key are deleted.

Using our previous example, if we deleted from the Ti tle table the row of data in the Ti tleID
column that now contains a value of 100, all rows in the Employee table that have a foreign key
reference to this deleted primary key would also be deleted.

This is useful in situations where related items should be deleted, such as for tables of suppliers and
their products. If you deleted the supplier, you would also want to delete the products they supplied.

Indexes
An index is an object that is associated with tables and is built using one or more columns from a table.
Just like an index in a book, it prOVides a means for looking up specific data. Indexes store information
from columns (usually primary and foreign key columns) along with the exact location of the associated
data within the table. Using an index to access information in a table is very efficient as SQL Server
makes use of the index to find the exact location of the row of data that you want retrieve or update.

19
Chapter 1

There are two different types of indexes in SQL Server - clustered and non-clustered.

Clustered indexes sort the data in the table rows by key. You can think of a clustered index as being
like a phone book. The columns that define the index (for example, the phone owner's last name then
their initial) are used to sort the table rows. This provides a very efficient means to access data in the
table. However, since a clustered index sorts the data in the table, there can be only one clustered index
for each table.

A clustered index actually stores the data rows of the table in the bottom leaf of the index. This means
that the index consists of the index entries pointing to each row of data, and the data rows are stored at
the end of the index.

Non-clustered indexes store the keys of the table in the index and contain pointers to where the data
actually resides in the table. The pointer in a non-clustered index is called a row locator because it
actually locates the row of data in the table. If the table does not have a clustered indexed defined, the
row locator in a non-clustered index contains a pointer to the row of data in the table. If a clustered
index is defined on a table, the row pointer contains the clustered index key. You can define as many
non-clustered indexes on a single table as you see fit.

Indexes can either be unique or not. Indexes that are unique do not allow duplicate keys (keys that
contain the same data value), while indexes that are not defined as unique may contain duplicate keys.
Index keys should not be confused with primary keys in a table. Any column in a table can be used as
the key column for an index.

Regardless of type, simply placing an index on your tables for the columns that are used to access data
will generally confer a speed advantage. This is true whether the access is by means of SELECT,
UPDATE, or DELETE statements. However, when you define an index on a table, SQL Server must
maintain the entries within that index and this requires extra overhead. This is usually offset by the
increased efficiency the index provides, especially for larger tables with thousands of rows or more.
Each INSERT, UPDATE, and DELETE statement performed against a table must also be used to update
the index. SQL Server automatically takes care of keeping the index in sync with the table.

When designing indexes for your tables, you should consider what types of SQL statements are going to
be used to select, insert, update, and delete data in your tables. You will usually want to define indexes
on columns that are specified in the WHERE, ORDER BY, and GROUP BY clauses. These will be covered in
detail later, for now an example of a SELECT statement that uses a WHERE clause is:

SELECT FirstName. LastName


FROM Employees
WHERE EmployeeID = 4

In this case we only select the first and last name from the Employee table where the EmployeeID has
a value of 4. If the EmployeeID column were defined as the index key, the SELECT operation would
be more efficient.

We will be working with indexes in Chapter 3 when we design and build our database. Actually
creating the indexes will help you to gain a better understanding of how to use and create them.

20
Introduction to SQL Server 2000

Defaults
Defaults are values that are automatically placed into a column when a new row of data is inserted and
no value has been specified for that column. In order to have a default value inserted, you must first
define the default and specify the columns to which it should apply. Default definitions are commonly
used to specify a zero for numeric columns, instead of having a null value inserted into them, as this
prevents problems when carrying out sorting operations, comparisons, or calculations.

Each column in a table can be assigned only one default. Identity columns cannot have defaults applied
to them nor can columns that contain the Rowversion data type, as the Rowversion data type is a
database-wide unique number.

A default value can be any constant or an expression that evaluates to a constant. For example,
expressions could be mathematical formulae or SQL Server functions, such as GETDATE () that returns
the current date and time.

When a column in a table does not allow null values and no default has been defined for that column,
you must specify a value for it when inserting data into the table or you will receive an error.

You can specify a default value for a column when a table is created, or you can alter the table and add
a default at a later date. However, if you apply a default to an existing table it is only applied to new
rows that are added - the existing rows are unaffected. You can also create a default as an object in the
database and share it between many tables. When created this way you can bind a default to multiple
columns in multiple tables.

Stored Procedures
A stored procedure is a group of T-SQL statements stored under a unique name and executed as a unit.
A stored procedure can have multiple T-SQL statements to perform such tasks as selecting data from
one table and updating data in another table.

As we mentioned earlier, SQL is an acronym for Structured Query Language. T-SQL is an acronym for
Transact Structured Query Language. SQL complies with the American National Standards Institute
(ANSI) SQL standards, while T-SQL is Microsoft's version of SQJ. that is based on ANSI SQL. The
latest version of ANSI SQL is referred to as SQL-99. Remember, any application that accesses SQL
Server does so through the use of SQL statements, which perform such actions as selecting data, and
creating and modifying the structure of your database.

Stored procedures should not be confused with queries, as queries are not stored in the database and
cannot be accessed by other applications. Queries are simply ad hoc T-SQL statements that you write
and execute in the Query Analyzer. They can be saved, but only as a file on your computer - SQL
Server does not know anything about them.

Stored procedures increase application performance. Firstly, there are less SQL statements to be
transmitted across the network as you only need to send the name of the stored procedure and any
parameters it requires. Secondly, stored procedures are parsed and optimized when they are created
and are compiled on the first execution, so they require less processing.

Stored procedures are similar to functions in other languages, as they can contain both input and output
parameters and can return values. They use logic to control the flow of processing, and there are
numerous functions and T-SQL statements that can be used in stored procedures.

21
Chapter 1

You can use stored procedures to execute routine functions such as selecting, inserting, updating, and
deleting data. A single stored procedure can be executed by multiple applications, thus providing code
reuse. Stored procedures can also be used to perform database functions, such as backing up your
database and transaction log. A simple stored procedure is listed in the following code fragment:

1D INTJ AS

itl

oy ID

Each stored procedure contains the CREATE PROCEDURE keywords to instruct SQL Server to create the
stored procedure. Then a name is assigned to the stored procedure, and any parameters it expects are
declared. The example listed here shows a name of up...parmsel_employee, and an input parameter
of @EmployeeID.

This is followed by the T-SQL statements and functions that are to be performed in the stored
procedure. In this example, the stored procedure will accept one input parameter, the employee ID, and
then select the employee's first name, last name, and title from the Employees table where the value in
the EmployeeID column matches the value in the @EmployeeID input parameter.

Stored procedures can be used to shield the complexities of the database from the users. All they need
to know is what stored procedure to execute and what parameters (if any) it expects, in order to get the
results they need. They do not need to know the relationship of the tables or even what tables exist in
the database.

SQL Server caches the stored procedure's execution plan in memory when the stored procedure is
executed. The cache is an area of memory that SQL Server uses to keep objects. Subsequent executions
of the stored procedure are executed using the copy in cache, thus optimizing the performance of your
application and SQL Server. SQL Server does a lot to optimize stored procedures, and using them has
many performance advantages over in-line SQL statements. In-line SQL statements are coded directly
into your program as a string and then sent to SQL Server for execution.

Chapter 7 will introduce stored procedures in more detail, and Chapter 8 explores the performance
benefits of using stored procedures over in-line SQL statements. We will learn how to create stored
procedures in SQL Server and then call them from our Visual Basic programs.

Triggers
Triggers are a special class of stored procedures and also contain T-SQL statements. However, instead
of executing a trigger like you would a stored procedure, a trigger is defined to execute automatically
when certain actions (insert, update, delete) are performed against a table. For example, you can define
a trigger that is to be executed when a DELETE statement occurs on a particular table. Then, when the
DELETE statement is processed, the trigger is executed by SQL Server. This trigger can perform such
actions as logging the record deleted and the user who performed the deletion.

Triggers are most often used to enforce the business rules and complex constraints that are defined by
your business requirements. Triggers can be used to create an audit record of the changes made to a row
of data, along with details of the user who made the changes. We will see this in action in Chapter 12
when we create our own triggers.

22
Introduction to SQL Server 2000

You can have multiple triggers for one table as long as each trigger has a unique name. Triggers can
also cause other triggers to be fired when an action is performed on another table that has a defined
trigger, thereby increasing their effectiveness and scope. Because triggers can contain complex
processing logic using T-SQL statements and functions, they are often used to help enforce data
integrity. This is especially true when one trigger calls another to delete related data. You can nest up
to 32 levels of triggers, having each perform an action that causes another to be executed, and so on.

Views
A view is like a virtual table containing data taken from one or more other tables. It is stored in the
database as the actual T-SQL statements that define the view, just like a stored procedure. When the
view is referenced, the virtual table is then created using the T-SQL statements contained in the view.

Views are generally used to let users see data from multiple tables all at the same time, thereby giving the
illusion that the data exists as a single table or group of data. The benefits of this are that it provides the
user with the illusion that all of their data is in one table, and hides the complexities of the database from
them. It also provides a security mechanism as we can grant users access to the view but not to the actual
tables from which it is derived, thereby limiting their access to only the data they are authorized to see.

Views can also be defined to be updateable. That is, they can actually update data that resides in
multiple tables. There are strict guidelines that must be adhered to in order for a view to update data in
the underlying tables. The view cannot use any aggregate functions in the SELECT list. Aggregate
functions are functions provided by SQL Server that perform calculations on the values in a column
from multiple rows, and return a single result. Also views cannot contain the TOP, GROUP BY, UNION, or
DISTINCT clauses that allow you to control how data is returned.

Views are flexible in that they allow you to execute other views and stored procedures to achieve the
end results. However, this flexibility only goes so far and there are some restrictions that are imposed on
views. For example, you cannot use the ORDER BY, COMPUTE, or COMPUTE BY clauses or the INTO
keyword. These will be defined in later chapters - they affect how data is returned and manipulated.

It is also not possible to use temporary tables within views. These tables are very similar to permanent
tables except they are stored in the TempDB database and are automatically deleted by SQL Server
when your session ends. Populating a temporary table is usually done using the INTO keyword within a
SELECT statement. As this keyword is not permitted in views, the temporary tables that depend on
them cannot be used either. We will cover temporary tables in detail later in this book.

OLE DB, ODBC, and ADO


Our VB and web applications do not communicate directly with SQL Server. We must use a data access
method such as ADO together with an Application Programming Interface (API) such as OLE DB or
ODBC that is designed specifically to access and expose the features of the various data stores. For
example, we might use an OLE DB for SQL Server driver or, if using Access, we could use an ODBC
for Access driver.

23
Chapter 1

The following diagram illustrates how these technologies fit in with SQL Server:

VB 01' Vi b
VB Applleatlon VB AppilcallOll
AppliC8\JOn

ADO
"
ROO OAO

SQl Server

SQL Server
Daumases

Let's take a look at each of these types of API in turn .

Open Database Connectivity (ODBC) is an API that allows lower-level languages, such as Visual C++,
to access various databases. ODBC is a high performance API used by tools, utilities, and system level
applications. It is an older technology that has been built upon by many database vendors and third
party suppliers of ODBC drivers.

ODBC is a complex API that even VC++ developers find hard to master. Given this, Microsoft built
several objects that reside on top of ODBC to make it more user-friendly. These include the Microsoft
Foundation Classes (MFC), Data Access Objects (DAO), and Remote Data Objects (RDO). These
provide an easier-to-use interface when compared with using ODBC directly, and most developers will
have used these objects at one time or another.

As time progresses, so does technology, and OLE DB (Object Linking and Embedding DataBase)
entered the scene. OLE DB is a low-level COM (Component Object Model) API that is used to access
information from just about any type of data store, not just databases. SQL Server ships with Microsoft's
version of the OLE DB API. This API provides high performance access to SQL Server and supports
the SQL-92 syntax, which makes it compliant with the OLE DB 2.0 specification. Tools, utilities, and
system-level development also use this API when high performance is needed.

While OLE DB provides an API that is easier to use than ODBC, it isn't ideal for every developer
because of its complex API interface. So ADO (ActiveX Data Objects) has been created as a COM
object to provide an interface with OLE DB. ADO provides an easy to use, lightweight COM object
suitable for general business applications. ADO is considered lightweight because of the size of its DLL
(Dynamic Link Library) when compared to those of DAO and RDO.

24
Introduction to SQL Server 2000

ADO has evolved from DAO and RDO, providing an interface that is easier to learn and use. It also
provides a feature set that most applications need to access data, whether that data resides in a flat file, a
database, or on the Internet. Because ADO is a COM object it can be used by any programming language
and technology that supports COM, for example Visual Basic, Visual C++, and ASP scripting languages.

Chapter 6 provides a general overview of the ADO object model, and a more detailed introduction to
ADO and how it can be used to enable database access from our VB and web applications.

XML
SQL Server 2000 provides native support for Extensible Markup Language (XML), a markup language
that is used to describe structured data. Not only can an XML document provide data but, through the
use of descriptive tags, it can also indicate the structure of that data. SQL Server 2000 provides native
support for this, meaning that you can select data from a table in SQL Server and have the results
returned as XML data. SQL Server 2000 also provides a useful utility to set up a virtual directory in
Internet Information Server (lIS) that allows the user to access a SQL Server database through the
Universal Resource Locator (URL) of a web page. A virtual directory prOVides the necessary association
between lIS and SQL Server.

What does all this mean? It means that you can query data in your database through the URL of a web
page. Take a look at the following URL:

http://LOCALHOST/NORTHWIND?SQL=SELECT+*+FROM+EMPLOYEE~+WHERE+EMPLOYEEID+=+l+FOR+XM
L+AUTO,ELEMENTS

This URL specifies a virtual root of NORTHWIND, which has been set up to point to the Northwind
database in SQL Server. The SQL SELECT statement selects a specific employee (with EmployeeID =
1) from the Employees table and returns the results. Notice all the plus signs in the URL. This is a
special character used to represent a space, as spaces are not allowed in a URL. This SELECT query
produces the following results:

- <EMPLOYEES >
<EmployeeID> 1 < / EmployeeID>
< Last Name > Davolio < /LastName >
< FlrstName> Nancy< /FlrstName >
<Title > Sales Representative <jTitle>
< TltleOfCourtesy > Ms. < jTltleOfCOurtesy>
< 61 rth Date> 1948-12-08TOO: 00: 00 < /6I rth Date >
< Hi reDate> 199 2-0S-01 TOO;OO; 00 < / HireDate>
< Address > S07 - 20th Ave. E. Apt. 2A < /Address>
<Clty > Seattle< /City >
< Region > WA< /Region >
< Posta1Code > 98122 < /PostaICode >
<Country > USA< /COuntry >
< HomePhone > (206) SSS-98S7 < / HomePhone>
,.,J: vt-n ........ inn ""' C;A,;~ "..

~~.~~--~=-=-----------==========w=~~==~~
,&:v ..,....r'tri,.....n .....
~

25
Chapter 1

As part of the native support for XML, SQL Server 2000 also provides a new keyword for the SELECT
statement called FOR XML. This new keyword returns data from the SELECT statement as XML
documents instead of the standard rows that we are used to.

This new keyword allows us to write queries and stored procedures that return data as XML. We can
then use these queries to return XML to our web pages and VB programs. In the previous example we
used an XML mode of AUTO. The mode determines the shape of the XML tree returned by SQL Server.
We also used the ELEMENTS argument, which specifies that columns in the table be returned as sub-
elements in XML. You can also define your own XML stylesheets, for example to display the data
returned from a SELECT statement in tables on your web page. These topics will be covered in more
depth in Chapter 15, where we'll take a closer look at the syntax and use of each of these features.

English Query
English Query is a separate product that ships with SQL Server 2000. It provides an environment for
creating applications that allow users to ask questions in natural English, instead of writing a SQL query to
retrieve the data they want to see. This makes the database accessible to even the most non-technical end
users, by concealing its underlying structure and negating the need to be conversant with SQL grammar.

For example, suppose a user wanted to know the title of Andrew Fuller in the Employees table of the
Northwind database. Instead of creating a SQL query to retrieve the information, they could simply ask
the question" What is Andrew Fuller's Title?". The English Query application would then build and execute
the appropriate SELECT query behind the scenes to retrieve the information and display it to the user.

English Query works best with normalized databases, so you should ensure that your database design
has been normalized. You must also ensure your database contains data so you can build, test, and train
your English Query application. It can then be published using Visual Basic or the Web, meaning that
you can deploy your English Query application though VB if your target audience is small, or use an
intranet or the Internet if your audience is great, or spread over multiple locations.

The case study (parts 1 and 2) provides an in-depth look at creating and deploying an English Query
application over the Web.

Analysis Services
Analysis Services, formerly known as OLAP, is a service that builds multidimensional cubes of data
retrieved from data warehouses (large databases that contain historical data about your business). These
multidimensional cubes contain both dimension and summary data held in cells, each addressed by a
set of coordinates that specify a position within the structure's dimensions. For example, imagine you
wanted to track sales of a number of components over a period of time - you could build a cube to
represent this data. In this case the dimensions would be component, sales, and time. The data would be
pulled from the data warehouses to build the results.

The data is used for analysis, and can be viewed from Microsoft Excel using the PivotTable service. If
you don't want to use Excel, you can also use ADO Multidimensional extensions to access the data.
Cubes of data can also be write-enabled so users can perform different scenarios on the data.

26
Introduction to SQL Server 2000

Because of the complexities of Analysis Services, SQL Server provides a number of wizards to help you
work with and build these data structures. There are wizards available to help you build the cubes of
data and also to create shared dimensions for use by other cubes.

Analysis Services was built as a technology to allow client applications efficient access to data stored in
data warehouses. It provides a multidimensional model making it easy for the user to navigate and
select information. You can use it to create views of data using ad hoc calculation functions, and to view
complex business data relationships.

You can process data from various data warehouse databases, such as SQL Server and Oracle (using OLE
DB). In fact, any database that supports OLE DB can be used as a data source for Analysis Services.

Part of Analysis Services functionality is a feature called Data Mining. It allows you to perform data
analysis and prediction within Analysis Services. Data Mining can be used to perform analysis of both
relational and multidimensional data. It provides the means to build Data Mining Models, which
contain predictive analysis of relational or multidimensional data.

Meta Data Services


Meta Data Services is a replacement for the Microsoft Repository found in earlier releases of SQL
Server. This new service actually builds on and expands the former version and provides an object
oriented repository technology that can be used by applications and systems that process meta data.

So what exactly is meta data? Meta data is information about data. That is, it provides property
information such as the type and length of the data in a column. It can also specify the structure of the
data or the design of objects, such as the cubes used in Analysis Services.

The Meta Data Services provides a way for you to store and manage meta data. SQL Server provides a
browser that allows you to view the data in the repository. This can be run from within the Enterprise
Manager or as a snap-in to the MMC console.

DTS
DTS (Data Transformation Services) is a component of SQL Server that provides graphical tools and
programmable objects enabling you to consolidate data from multiple sources into a single source. Not
only are you able to consolidate data, you are also able to extract and transform the data from multiple
sources prior to consolidation.

DTS is based on the OLE DB architecture and allows you to copy and transform data from Oracle to
SQL Server using native OLE DB providers. For data sources that do not support OLE DB, SQL
Server's OLE DB provider can use ODBC to copy and transform data. SQL Server itself uses DTS to
copy and transfer data and objects from one SQL Server installation to another.

27
Chapter 1

Summary
This chapter has introduced SQL Server 2000 at a high level. We have covered the basics of SQL
Server 2000 and have found that it is actually a family of products that combine to make up a very
powerful and rich relational database, loaded with features.

We have also explored databases in SQL Server and now know that they are made up of several
different objects, such as tables, keys, and indexes. Having explored the various database objects, we
can now see how they all work together to help provide secure and reliable data. Through the use of
primary and foreign key constraints, SQL Server can enforce the rules of referential integrity, which
helps to ensure that our data is reliable and consistent.

We took a quick look at how our applications communicate with SQL Server, and learned that ADO
provides an easy-to-use object model that simplifies this communication process.

Having briefly covered some of the other features of SQL Server 2000, such as XML support, English
Query, Meta Data, and Analysis Services, we can see that SQL Server 2000 has a lot to offer through
additional complementary features and services.

We saw how the XML features of SQL Server 2000 allow us to access data residing in our databases
over the Web, or through VB programs. We also discovered that SQL Server provides native support to
return the data in XML format straight from the database.

To summarize, you should:

o Understand SQL Server databases and transaction logs at a high level


o Be aware of the various objects that make up a SQL Server database
o Understand tables, keys, and indexes
o Know that we can use stored procedures and views to extract data for viewing
o Be aware of the existence of data access technologies, such as ADO
o Know that SQL Server 2000 provides native support for XML
o Know that we can use English Query to build a simple user-friendly interface that allows users
to query our database by asking questions in natural English

In the next chapter we will install the Personal Edition of SQL Server 2000 and cover some of the tools
that are available. This will help set the stage for the chapters that follow, as you become familiar with
the user interfaces of SQL Server 2000.

28
Installing the Personal Edition
of SQL Server 2000

Having just had an overview of SQL Server 2000, you are probably ready to install this product and
begin working with it. This chapter will help you do just that.

SQL Server 2000 comes in several different editions, each designed to meet a specific need. And while
we will briefly cover each of these editions, our main focus will be on the Personal Edition of SQL Server
2000. This edition provides most of the features available and allows us to install it on our workstations.

We will cover the supported platforms for each edition and the prerequisites for installing the Personal
Edition. We will then go through the installation process, explaining each step.

Once our installation has been completed, we will take a tour of the Enterprise Manager to acquaint you
with the features of this tool. This is the main user interface used to administer databases in SQL Server.
We will also take a brief look at some of the other tools and wizards that come with SQL Server, which
help to simplify various administrative tasks.

In this chapter, we will:

o Discuss the differences in the SQL Server 2000 editions and suitable platforms
o Cover SQL Server 2000 prerequisites
o Step through installing SQL Server 2000 and SQL Server instances
o Tour the Enterprise Manager
o Preview the Query Analyzer and SQL Profiler
o Preview common wizards
Chapter 2

SQL Server Editions and Platforms


As we mentioned above, SQL Server 2000 comes in many editions. This section will examine some of
the high level features of each edition and identify the platforms that each will run on. While this list
will not be exhaustive, it should serve to give you a good idea of the supported features in each edition.
In addition, this list will also let you know what editions are available should you need to identify a
suitable edition for your business.

Enterprise Edition
We start with the Enterprise Edition. This is a full-featured edition of SQL Server 2000, and scales to
meet the demands of the largest web sites and data warehousing applications. The Enterprise Edition of
SQL Server 2000 is the edition that most companies would run in an environment where SQL Server
needs to be clustered and the volume of transactions is high. You would most likely find this edition
installed at dotcom-type companies where there is a high volume of online transactions.

This edition contains features such as Full-Text Search, Multiple Instance Support, Log Shipping, and
Failover Clustering.

Full-Text Search is a feature of SQL Server that allows you to search for words or phrases in a character
column of a table. Multiple Instance Support means that multiple named instances of SQL Server can
be installed on the same machine. Log Shipping is a feature that allows you to have transaction logs
automatically shipped to a SQL Server installed on another machine and recorded. This provides a hot
standby machine in case the primary SQL Server machine fails. Failover Clustering provides a means of
having SQL Server failover onto another SQL Server on a cluster of machines should a hardware failure
occur on the node that SQL Server is running on.

The Enterprise Edition runs on server operating systems only:

o Windows NT 4.0 Server


o Windows NT 4.0 Server Enterprise Edition
o Windows 2000 Server
o Windows 2000 Advanced Server
o Windows 2000 Datacenter Server

Similar to the Enterprise Edition is the Enterprise Evaluation Edition. This is a full-featured evaluation
edition of SQL Server 2000 that will expire after 120 days. The Enterprise Evaluation Edition will run
on the same operating systems as the Enterprise Edition. You can download this evaluation edition for
free at http://www.microsoft.com/sql/.

Developer Edition
The next edition available is the Developer Edition. This edition of SQL Server 2000 has all of the
functionality and features of the Enterprise Edition but is licensed only for development and testing. You
cannot legally run this edition of SQL Server in a production environment. This edition will run on:

o Windows 98
o Windows NT 4.0 Workstation
o Windows NT 4.0 Server

32
Installing the Personal Edition of SQL Server 2000

o Windows NT 4.0 Server Enterprise Edition


o Windows 2000 Professional
o Windows 2000 Server
o Windows 2000 Advanced Server
o Windows 2000 Datacenter Server

If running this edition on Windows 98, the Desktop Engine is used, which provides less functionality
(for example, no Full-Text Search). The Desktop Engine will be covered shortly.

Personal Edition
The Personal Edition of SQL Server was primarily designed for mobile computing users. This edition of
SQL Server is also ideal for applications that need a standalone installation of SQL Server on the client
machine. This edition will run on:

0 Windows 98
0 Windows NT 4.0 Workstation
0 Windows NT 4.0 Server
0 Windows NT 4.0 Server Enterprise Edition
0 Windows 2000 Professional
0 Windows 2000 Server
0 Windows 2000 Advanced Server
0 Windows 2000 Datacenter Server

The Full-Text Search and Multiple Instance features are supported in this edition, however the Full-Text
Search features are not available when running Windows 98.

Standard Edition
For small workgroups and departments SQL Server Standard Edition fits the bill, and should provide
all the functionality needed by these groups of users. This edition runs on server operating systems only:

o Windows NT 4.0 Server


o Windows NT 4.0 Server Enterprise Edition
o Windows 2000 Server
o Windows 2000 Advanced Server
o Windows 2000 Datacenter Server

This edition also supports the Full-Text Search and Multiple Instance features.

33
Another Random Scribd Document
with Unrelated Content
The Project Gutenberg eBook of Histoires
magiques
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: Histoires magiques

Author: Remy de Gourmont

Release date: September 8, 2020 [eBook #63147]


Most recently updated: October 18, 2024

Language: French

Credits: Produced by Laurent Vogel and the Online Distributed


Proofreading Team at https://www.pgdp.net (This file was
produced from images generously made available by the
Bibliothèque nationale de France (BnF/Gallica) at
http://gallica.bnf.fr)

*** START OF THE PROJECT GUTENBERG EBOOK HISTOIRES


MAGIQUES ***
REMY DE GOURMONT

Histoires magiques
DIXIÈME ÉDITION

PARIS
MERCVRE DE FRANCE
XXVI, RVE DE CONDÉ, XXVI

MCMXXIV

DU MÊME AUTEUR,

Roman, Théâtre, Poèmes.

SIXTINE.
Le Fantôme. Le Château singulier. Théâtre
LE PÈLERIN DU SILENCE.
muet. Le Livre des Litanies. Pages retrouvées.
LES CHEVAUX DE DIOMÈDE.
D'UN PAYS LOINTAIN.
LE SONGE D'UNE FEMME.
LILITH, suivi de THÉODAT.
UNE NUIT AU LUXEMBOURG.
UN CŒUR VIRGINAL. Couverture de G. d'Espagnat.
COULEURS, suivi de CHOSES ANCIENNES.
HISTOIRES MAGIQUES.
DIVERTISSEMENTS, poésies complètes, 1912.

Critique, Littérature.

LE LATIN MYSTIQUE (Étude sur la poésie latine du moyen âge) (Crès,


éditeur).
LE LIVRE DES MASQUES (Ier et IIe), gloses et documents sur les
écrivains d'hier et d'aujourd'hui, avec 53 portraits par F. Vallotton.
LA CULTURE DES IDÉES.
LE CHEMIN DE VELOURS. Nouvelles dissociations d'idées.
LE PROBLÈME DU STYLE. Questions d'Art, de Littérature et de
Grammaire.
PHYSIQUE DE L'AMOUR. Essai Sur l'instinct sexuel.
ÉPILOGUES.Réflexions sur la vie, 1895-1898; 1899-1901 (2e série);
1902-1904 (3e série); 1905-1912 (volume complémentaire); 4
vol.
ESTHÉTIQUE DE LA LANGUE FRANÇAISE, édition revue, corrigée et
augmentée.
PROMENADES LITTÉRAIRES (1re, 2e, 3e, 4e et 5e séries); 5 vol.
PROMENADES PHILOSOPHIQUES (1re, 2e et 3e séries); 3 vol.
DIALOGUES DES AMATEURS SUR LES CHOSES DU TEMPS (Epilogues, 4e série,
1905-1907).
NOUVEAUX DIALOGUES DES AMATEURS SUR LES CHOSES DU TEMPS
(Epilogues, 5e série, 1907-1910).
DANTE, BÉATRICE ET LA POÉSIE AMOUREUSE.
PENDANT L'ORAGE.
LETTRES A L'AMAZONE.
PENDANT LA GUERRE.
LETTRE D'UN SATYRE.
LETTRES À SIXTINE.
PAGES CHOISIES, avec un portrait.

IL A ÉTÉ TIRÉ DE CET OUVRAGE:

Trois exemplaires sur Japon impérial


numérotés de 1 à 3
et dix-sept exemplaires sur hollande Van Gelder
numérotés de 4 à 20.

JUSTIFICATION DU TIRAGE

Droits de traduction et de reproduction réservés pour tous pays.


PÉHOR

Nerveuse et pauvre, imaginative et famélique, Douceline fut


précocement caresseuse et embrasseuse, amusée de passer ses
mains le long de la joue des garçonnets et dans le cou des fillettes
qui se laissaient faire comme des chattes. Elle se mettait, à propos
de rien, à baiser les mains tricotantes de sa mère, et quand on la
reléguait en pénitence sur une chaise, elle jouait à faire claquer ses
lèvres sur ses paumes, sur ses bras, sur ses genoux, qu'elle dressait
nus l'un après l'autre; alors elle se regardait. Telle que les curieuses,
elle n'avait aucune pudeur. Comme on la grondait en termes
grossièrement ironiques, elle se prit d'une tendresse de contradiction
pour le coin méprisé et défendu; les mains suivirent les yeux. Elle
garda ce vice toute sa vie, ne s'en confessa jamais, le dissimula avec
une effrayante astuce jusque parmi ses crises d'inconscience.
Les exercices préparatoires de la première communion la
passionnèrent. Elle quémandait des images, des sous pour en
acheter, volait celles de ses compagnes dans leurs paroissiens. Les
Saintes Vierges lui plaisaient peu; elle préférait les Jésus, les doux,
ceux dont les joues lavées de rose, la barbe en flammes, les yeux
bleus s'inscrivaient dans la diffuse lumière d'une auréole. L'un, avec
une visitandine à ses pieds, lui montrait son cœur rutilant, et la
visitandine articulait: «Mon bien-aimé est tout à moi et je suis toute
à lui.» Sous un autre Jésus aux regards tendres et un peu loucheurs,
on lisait: «Un de ses yeux a blessé mon cœur.»
D'un Sacré-Cœur piqué par un poignard giclait du sang couleur
d'encre rose, et la légende, avilissant une des plus belles
métaphores de la théologie mystique, portait: «Qu'est-ce que le
Seigneur peut donner de meilleur à ses enfants que ce vin qui fait
germer les vierges?» Le Jésus d'où fusait ce jet de carmin avait une
face affectueuse et encourageante, une robe bleue, historiée de
fleurettes d'or, de translucides mains très fines où s'écrasaient en
étoile deux petites groseilles: Douceline l'adora tout de suite, lui fit
un vœu, écrivit au dos de l'image: «Je me donne au S. C. de Jésus,
car il s'est donné à moi.»
Souvent, entr'ouvrant son livre de messe, elle contemplait la face
affectueuse et encourageante, murmurait, en la portant à sa
bouche: «A toi! A toi!»
Quant au mystère de l'Eucharistie, elle n'y comprit rien, reçut
l'hostie sans émotion sans remords de ses confessions sacrilèges,
sans tentatives d'amour: tout son cœur allait à la face affectueuse et
encourageante.
Cependant, comme succédané au catéchisme de persévérance,
on lui fit lire «le Bouclier de Marie». Un passage où était notée la
préférence de Jésus pour les belles âmes et son dédain des beaux
visages l'intéressa. Elle se regarda, des heures entières, dans un
miroir, se jugea jolie, décidément, eut du chagrin, souhaita d'enlaidir,
pria avec ferveur, se donna la fièvre, se réveilla un matin avec des
boutons plein la figure. Dans le délire qui suivit, elle proférait des
mots d'amour. Guérie, elle remercia Jésus des marques blanches qui
lui trouaient le front, se livra à de longues éjaculations, à genoux,
derrière un mur, sur des pierres aiguës. Ses genoux saignaient: elle
baisait les blessures, suçait le sang, se disait: «C'est le sang de
Jésus, puisqu'il m'a donné son cœur.»
Affaiblie par l'anémie de la fièvre, elle avait pendant des
semaines, oublié son vice: les mouvements habituels se
recomposèrent dans le sommeil. Elle se réveillait à moitié polluée, se
rendormait. Un matin, ses doigts furent ensanglantés; elle eut peur,
se leva vite, mais le sang était partout. Sa mère dormait. Elle
arracha du paroissien où elle l'avait cousue, l'image vouée, sortit en
chemise, tremblante, alla l'enterrer dans un trou profond. Pleurante,
elle revint, s'évanouit.
Les explications de sa mère, il fallut bien les croire. Pourtant, ce
n'était pas naturel. Elle accusa le Jésus que, d'instinct, elle avait
étouffé sous la glèbe, qui accueille en son silence les trépassés. Le
Jésus du sang était mort. Elle se calma, pendant que sa mère la
recouchait, lui donnant à lire la Vie des Saints.
Douceline lut la Vie des Saints, emmagasinant des noms étranges
qui lui revenaient aux oreilles, quand elle somnolait, tels que des
sons de cloches: un nom entre tous, sonnait, plus bruyant que les
trois cloches des grands dimanches, sonnait et quatrissonnait dans
sa cervelle: Pé-hor-Pé-hor-Pé-hor-Pé-hor.
Les démons sont des chiens obéissants. Péhor aime les filles et il
se souvient des jours où il exaspérait le sexe de Cozbi, fille de Sur, la
royale Madianite: il vint et il aima Douceline pour l'amour de sa
puberté neuve et déjà souillée; il se logea dans l'auberge du vice,
sûr d'être choyé et caressé, sûr de l'obscène baiser des mains en
fièvre, sans craindre le glaive de Phinée, qui avait tranché d'un seul
coup jadis les joies de Cozbi et les joies de Zambri, alors que le fils
de Salu était entré dans la fille de Sur.
La chambre au milieu de la nuit s'éclairait, et tous les objets
semblaient auréolés, comme devenus lumineux par eux-mêmes,
avec des propriétés d'irradiation. Alors, accalmie: et dans une ombre
rousse qui fermait toutes les portes visuelles, il venait. Elle le sentait
venir, et tout aussitôt des frissons commençaient à voyager le long
de sa peau, faiblement, puis nettement localisés. Les lumières
messagères entraient à travers l'ombre rousse, s'insinuant en toutes
ses fibres, puis rien que de l'ombre rousse et, à l'improviste, de vifs
jets de lumière douce, en rythme précipité; enfin, une explosion
comme de feu d'artifice, un craquement exquis où fuselait sa
cervelle, son épine, ses moelles, ses muqueuses, les pointes de ses
seins et toutes ses chairs dépidermées; tous ses duvets érigés
comme des herbes que rebrousse un vent rasant. Et après le dernier
sursaut, des petits frissons intérieurs: par les valvules entr'ouvertes,
du plaisir filtré filait dans les veines vers toutes les cellules et toutes
les papilles. Péhor, à ce moment, sortait de sa cachette, se
grandissait en un jeune beau mâle que Douceline, sans étonnement,
admirait amoureuse. Elle le couchait la tête à son épaule,
s'endormait, consciente seulement qu'elle tenait entre ses bras
Péhor.
Dans la journée, elle se complaisait au souvenir de ses nuits, se
délectait à l'impudicité des phases, à l'acuité des caresses, aux
foudroyants baisers de Péhor invisible et intangible tant que durait le
plaisir, surgissant, tel que magiquement, après l'éclosion parfumée
des joies. Qui, ce Péhor! Elle ne le sut jamais, insoucieuse de tout,
hormis de jouir, très abêtie par la multiplicité des spasmes, vivant
dans un songe charnel, et, Psyché vierge de l'homme, instauratrice
de ses propres débauches, elle s'abandonnait à l'ange ténébreux
dans l'ombre rousse ou dans la fulgurance des luminosités
cérébrales, sans volonté comme sans réticences.
Elle atteignait quinze ans, lorsque, dans le pâquis où elle gardait
la vache de la famille, un colporteur abusa de son sommeil de fille
énervée. Ne souffrant pas, amplement déflorée par Péhor dont les
imaginations étaient audacieuses, elle laissa faire. Les grimaces de
l'homme lui parurent ridicules, et comme il la regardait, redressé,
avec des yeux amoureux, elle se leva, éclata de rire, s'éloigna en
haussant les épaules.
Elle fut punie de s'être laissé faire: Péhor ne revenait plus.
En gardant sa vache, dans le pâquis, elle rêvait maintenant du
colporteur, non sans honte. Après des semaines, une peur lui vint, et
comme elle avait vu des femmes grosses mettre des cierges à la
bonne Vierge afin d'accoucher heureusement, elle en fit piquer un
très gros sur la herse, pour ne pas grossir.
Exaucée, elle eut de la reconnaissance, s'adonna à des prières,
quittait sa vache et le pâquis, venait égréner, à genoux sur les dalles,
de longs chapelets devant la bienfaisante image: elle lui trouvait,
comme jadis au Jésus, la face affectueuse et encourageante.
Cependant, son vice, même sans Péhor, la rongeait. Ses joues se
creusèrent, elle toussa, l'épine dorsale devint sensible, des
étourdissements la prenaient, la couchaient sous les sabots de la
vache, qui se mettait à la flairer en meuglant. Un matin, elle trembla
si fort qu'elle ne put mettre ses bas. Recouchée, elle souffrit au
ventre: les ovaires enflammés palpitaient sous la piqûre d'un paquet
d'aiguilles.
En l'ennui de ce lit désolant, des imaginations la visitèrent, d'une
candeur inattendue, rappel de l'innocence première. Elle vit
successivement, en de fausses extases, le Bon Dieu, tout blanc,
pareil au Prémontré qui avait une fois prêché le carême; de petits
saint Jean d'argent jouant sur la mousse des bosquets célestes avec
des agnelets frisés et enrubanés, un Notre Seigneur tout en or, avec
une longue barbe rouge, une Sainte-Vierge nuageuse et bleuâtre.
Pendant les derniers jours, les consolantes apparitions
l'abandonnèrent, comme par une négation du ciel à de plus longues
complicités. L'hypocrisie infernale fut vaincue et la pécheresse
impénitente rendue à celui que d'infâmes épouvantes avaient fait
son maître éternel. Péhor revint se loger dans l'habitacle secret des
impuretés consenties, et Douceline se sentait ravagée par des
caresses douloureuses, des effleurements lents d'orties, des
promenades vives de fourmis dans la turgescence presque putride
de son sexe mûri jusqu'à craqueler comme une figue. Et elle
entendait, heures d'irrémissible agonie! le rire de Péhor sonner en
son ventre tel que le glas de la soirée du jeudi saint, qui semble
sortir des tombes. Péhor s'adonnait au rire de la satisfaction
démoniaque et par plaisanterie il se gonflait comme une outre au
moyen des vents empestés qu'il laissait bruyamment sortir, tout d'un
coup. Puis il se mettait à la baiser amoureusement, et un ironique
coup de dent se substituait au spasme. Douceline criait, mais il lui
semblait que Péhor criait plus fort, emplissait de stridences aiguës
son abdomen qui tremblait sous les vibrations… Il y eut dans l'asile
immonde un grand remue-ménage, puis ce fut vers l'épigastre une
sensation terrible de tassement et d'étouffement: Péhor montait. En
passant il enfonça ses griffes dans le cœur de Douceline, il déchira,
en s'y accrochant, les trous d'éponge du poumon, puis le cou se
gonfla comme un serpent qui revomirait sa proie engluée, et de
larges bavures de sang jaillirent de l'ignominie d'un hoquet
d'ivrogne. Elle respira, évanouie presque, les yeux clos, les mains
ramant parmi les vagues molles du naufrage, qui emportait la
damnée aux abîmes… Un baiser d'excrémentielle purulence
s'appliqua sur ses lèvres exactement, et l'âme de Douceline quitta ce
monde, bue par les entrailles du démon Péhor.
LA ROBE BLANCHE

A Louis Denise.

Ah! comme je regrettais le coin de wagon où, rudement bercé, je


rêvais à des paysages plus inquiétants que les moulins muets, les
clochers seuls, les pommiers penchés et les dolentes masures,—sous
la brume nocturne, le sommeil exaspéré d'une nature enfin libérée
du soleil et du rire, des sueurs et des pleurs!
Témoin choisi des cérémonies prévues d'un mariage, je venais
assister mon camarade, Albéric de Courcy. Déjà, tels amis avaient,
pour de pareilles fêtes, requis ma complaisante indifférence: je ne
me permets jamais de prendre une trop visible part aux joies des
autres, ni à leurs deuils; ma tenue est la dignité affectueuse, et le
sourire habituellement morne et assez doux de mes yeux grisaille
leur fait pardonner les flammes qui parfois signalent la révolte d'un
regard résigné.
Nul messager: on ne m'attendait que le lendemain matin. Je fis le
trajet, trois quarts d'heure de marche par les bois, en évitant les
clairières et la fadeur de l'éternel clair de lune.
Sans trop m'émouvoir de l'absurdité d'une survenue, la nuit, dans
une maison endormie, j'invoquai, pour découvrir le château des
Joncs, le souvenir d'antérieures visites: la grille n'était encore que
poussée.
Aucun chien ne hurla, j'avais l'air d'un habile voleur.
Je franchis des gazons qui abrégeaient le cercle des grandes
allées, et au détour d'un groupe de syringas, oh! parfum cruel!
j'aperçus, dans la triste blancheur d'une façade morte, deux fenêtres
côte à côte illuminées.
C'était au rez-de-chaussée. Avant de frapper à la vitre, j'eus
l'impudence de regarder:
Au milieu d'un petit salon très en désordre, trois femmes
considéraient une robe blanche jetée sur un fauteuil, une robe plus
blanche que l'âme des saints Innocents: Rosa, la pierre ancillaire de
cette maison, Mme de Laneuil et une jeune fille,—dont le profil me
remémorait des amours enfantines et un temps où de rieuses
gamines en robes adolescentes nous donnaient, à Albéric et à moi,
les fleurs de leurs corsages, après les avoir approchées, avec la
soudaine gravité d'immortelles fiancées, du saint-sacrement de leurs
lèvres!
Il y avait de cela, combien? des années, de longues années,
peut-être dix? Ah! souvenir des jeunes concupiscences! Depuis, que
de fois les merles avaient salué le sommeil au faîte des lourds
marronniers! La mort de M. de Laneuil était venue clore la maison,
Albéric n'en avait retrouvé le chemin que pour y choisir une femme,
et moi, pour témoigner à ce choix de l'inutile approbation du monde.
Edith, Elphège: il épousait Edith, l'aînée, et celle que je voyais,
blonde et pâle, plus pâle du prochain sacrifice que la sacrifiée elle-
même, choéphore plus troublée que la victime, assistante plus
tremblante que l'hostie, celle que je voyais et dont le profil me
remémorait les jeunes concupiscences des amours enfantines, c'était
Elphège,—sans aucun doute Elphège, la pâle, la blonde Elphège…
Rassuré par le fantôme de raisonnement qui tendait vers moi ses
mains ironiques, j'acceptai joyeusement la fascination: je
contemplais le double rayonnement d'un double cortège, aux pieds
du prêtre quatre coussins rangés, et j'entendais les multiples
anneaux d'or sonner dans la patène:—pourquoi tant d'anneaux d'or?
C'était Elphège,—sans aucun doute Elphège, et je l'aimais d'une
telle convoitise que je crus l'avoir aimée, heure par heure, pendant
les années de mon exode.
Aimée, oui! Et alors je la vis grandissante, le rire à mesure
s'affinant en sourire, les yeux occupés à la divination des joies
futures, et j'écoutai la mort brève des vaines harmonies suscitées en
des soirs d'orage, et je perçus toutes les langueurs de celle qui
attend le messie des aurores adamantines, et j'assistai aux innocents
réveils, quand les merles saluent le soleil au faîte des lourds
marronniers.
Les cruels syringas m'enveloppaient de vertiges…
Je frappai à la vitre.
Les trois sœurs tressaillirent.
Après de l'indécision, Rosa, sur un ordre, demanda, en écartant
le léger rideau, en se faisant des œillères avec les mains: «Qui est
là?»
L'ombre extérieure répondit par son nom: Mme de Laneuil
disparut; la jeune fille souriait, Elphège,—sans aucun doute Elphège!
J'étais le bienvenu, on faisait bonne mine au visiteur attardé.
La porte se débarricada, j'entrai, reçu par ma vieille amie qui
m'examinait, le flambeau levé comme une torche pour s'assurer que
c'était bien moi, non pas un habile voleur.
«Comme vous êtes pâle!»
Ainsi répondit-elle à mes douteuses cordialités.
Je m'excusai sur l'influence vraiment excessive qu'exerçaient en
cette nuit spéciale les blancheurs lunaires.
«Et nous, mon ami, et nous! reprit-elle, mystérieusement, en
abaissant son flambeau. Ah! c'est un inconcevable sortilège! Figurez-
vous… Tout le monde, notamment lui, s'est retiré de bonne heure,
Elphège est souffrante, accablée par cette énigmatique inquiétude
des filles dont la sœur se marie… Je voulais qu'il fût permis à Edith,
avant de reposer seule pour la dernière fois, de s'envelopper, comme
d'un manteau béni, d'une longue et virginale prière… Nous allions
monter à ma chambre, lorsque la robe nous est revenue de Paris…
la robe blanche!… Une retouche au corsage… Rosa avait épinglé…
Rien!… Ils la renvoient telle… Et c'est trop large de ça!»
Deux doigts.
«De ça!… Nous sommes consternées!… Et voici le sortilège, nous
discutons, nous prenons les ciseaux chacune à notre tour, et
personne n'ose découdre,—et pourtant il le faut! J'ai peur que nous
ne passions la nuit…»
D'une voix plus blanche que la robe ensorcelée, je demandai, en
me contraignant, avec adresse, à la plus aimable désinvolture:
«Tout en frappant à la vitre, j'ai aperçu, bien involontairement,
l'une de vos filles, et je l'avais prise pour Elphège,—sans aucun
doute Elphège…
—«Elles se ressemblent tant, et il y a si longtemps! Ah! l'heureux
jadis!… Mais, j'y songe, venez! Les hommes ont plus de sang-
froid…»
Elle répéta:
«Venez!»
Quand je pénétrai, à la suite de sa mère, dans le petit salon,
Edith, d'un regard froid et dur, m'interrogea sévèrement, mais Mme
de Laneuil, consciente, elle aussi, de la profanation imposée par ma
présence à cette veillée anténuptiale, en dissipa hâtivement les
ténèbres, exposa, avec des rires, ce qu'elle appelait son idée…
Et moi je songeais que c'était bien Edith,—sans aucun doute
Edith! C'était bien la pâle Edith que j'aimais, la blonde Edith, avec
toute la violence d'une désolante insanité! Seul avec elle, j'aurais en
vérité subi les horribles tentations du stupre, j'aurais voulu boire la
rosée de sang répandue sur ces lèvres muettes…
Mme de Laneuil exposait, avec des rires, son idée…
Et moi, mon agitation nerveuse m'abandonnait, vaincu, à une
familière crise de désolation consentie, lorsque je devinai qu'Edith
me regardait encore, me regardait toujours:—sans aucun doute,
Edith me regardait.
Je levai vers ses yeux des yeux où, tout soudain, ainsi que dans
un vertigineux changement de décor, j'avais, par les plus
impérieuses flammes du désir, remplacé l'indifférence:—Elle accepta,
et, après une infinie seconde de pénétration mutuelle, ses paupières
tombèrent pour se relever vite et m'avouer l'unisson absolu de sa
volonté…
Mme de Laneuil s'adressait à moi:
«Voyons, qu'en pensez-vous? un bon conseil!»
Je me secouai, presque radieux des joies inattendues de cet
adultère idéal, si bien qu'elle s'aperçut d'une transformation dans
mon attitude:
«Ah! le voilà réveillé! On a beau dire, un mariage, voyez-vous, ce
n'est jamais triste!»
Edith souriait tristement.
«Mais, il faudrait, dis-je, avec un bon sens qui me fit honneur
devant ces trois femmes, il faudrait que Mlle Edith voulût bien la
mettre, la robe…
—«C'est vrai, il faut qu'elle la mette!»
Avec mes mains pour œillères, comme Rosa, je regardais par la
fenêtre… La lune, maintenant, couchait au travers de la cour la
projection écrasée de la lourde maison seigneuriale… Une autre
vision m'ôta l'usage de mes prunelles: Je suivais, guidé par les
froissis de l'étoffe, le bruit des boutons et des agrafes, toutes les
phases de la métamorphose qui s'œuvrait derrière moi, et, comme
j'entendais, je voyais,—par une instantanée transposition des sons
en images,—je voyais la gorge ingénue de mon Amour, et une rapide
main ramenant l'épaulette glissée, et le mouvement des bras libérait
des effluves aussi violents et plus cruels que l'odeur des syringas, et
sous la pointe du corset, comme ils fleurissaient larges et amers les
cruels syringas!… La robe blanche, telle qu'une avalanche, s'abattit
sur mon rêve…
Edith souriait tristement.
Ce furent des conciliabules de couturières.
Je donnai mon avis, qu'on accepta. Rosa se mit à découdre, à fin
de quelques remplis à résorber, et je voyais, dans son regard
respectueux, de l'estime.
Avant de sortir, précédé de Mme Laneuil, qui me conduisait à ma
chambre, je saluai la jeune fille avec cette discrétion qu'impose
l'accord tacite de deux âmes compromises dans le même secret. Ses
jeux suivaient les miens, ses clairs yeux bleus à la transparence
attendrie…

. . . . . . . . . . . . . . . . . . . .

Depuis longtemps les merles avaient salué le soleil au faîte des


lourds marronniers: Albéric entra chez moi. Les lendemains!
Quelques doutes le tourmentaient: il me les confessa avec la naïveté
de ces êtres inquiets et bons qui croient trouver en autrui une
sympathie. Je le laissai dire, cela me reposait, car, ainsi que
l'enseigne la morale des Proverbes, il faut, en état de déréliction,
regarder autour de soi: d'autres douleurs s'exhalent, et cela console.

. . . . . . . . . . . . . . . . . . . .

Ah! je pense au saint-sacrement de ses lèvres!

. . . . . . . . . . . . . . . . . . . .

L'Apparition: un murmure l'annonça. Edith fit son entrée dans le


grand salon morne, sous les regards indulgents des ancêtres. Les
yeux n'avaient pas pleuré, mais n'avaient pas dormi: une ombre se
creusait autour de leurs pâles saphyrs.
Le corsage dont j'avais corrigé l'esthétique cuirassait étroitement
la Vierge sous le grand voile blanc.
S'écartant du chœur, elle se dirigea, lente et suivie de tous les
regards, vers son grand-père, vieillard presque douloureusement
ému qui s'appuyait à la cheminée,—et, en passant près de moi, sans
à peine remuer les lèvres, la bouche entr'ouverte comme un soupir,
les yeux baissés sur l'effondrement de nos espoirs d'une heure, elle
me fit entendre ces seuls mots:
«Il est trop tard!»
Moi aussi, je baissai les yeux, dévorant en mon âme la joie
maudite des occultes compromissions.
Elle offrit sa grâce au baiser du vieillard, et, les deux mains sur
ses épaules, elle lui souriait.
Edith souriait tristement.
Le consentement de toute la race tomba, comme une
bénédiction, sur le front de la fiancée.
J'étais près d'eux: le grand voile flottait autour de ma tête, car le
vent d'une fenêtre ouverte l'avait gonflé, et il me sembla qu'un
souffle de passion nous envolait, Edith et moi, la pâle, la blonde
Edith et moi, vers le paradis des amants parjures.
Revenue aux côtés de sa mère, elle fixa un instant sur moi ses
yeux assombris, puis, brusquement, sous le tulle déroulé, se déroba
toute,—à jamais!
L'ironie des cruels syringas entra par la fenêtre ouverte.
Elle fut mariée.
Pendant la cérémonie, il me plut de répondre tout bas: oui! à
l'interrogatoire du prêtre, et je courbai la tête quand les mains
sacerdotales s'étendirent pour ratifier, au nom du Très-Haut, le
serment sacré des deux époux.
Alors, me remémorant de vieilles études théologiques, je songeai
qu'en tout sacrement il y a la matière et la forme, l'essence et le
mode imposé par les rites pour en dispenser aux fidèles les bienfaits
mystiques: et dans le mariage, la forme, ce n'est pas la bénédiction
de l'officiant, ce n'est pas la messe, c'est le consentement mutuel,—
et cela seul.
«Va, femme d'un autre, bien que le monde doive me refuser les
joies, après tout bien dérisoires, de la possession, de ce qu'il appelle
la possession,—en vérité, tu m'appartiens. Notre Dieu connaît notre
mutuelle volonté, et cela suffit—cela seul.»
Et je me réjouissais amèrement, car le prêtre disait: «Qu'elle soit
uniquement attachée à son mari et qu'elle ne souille d'aucun
commerce illégitime le lit nuptial…»
Je partis, tel qu'un voleur.
Les merles ne chantaient pas encore au faîte des lourds
marronniers et les cruels syringas dormaient enfin,—fanés, aussi
fanés que les souvenirs des jeunes concupiscences…
LE SECRET DE DON JUAN

… Et simulacra modis pallentia miris.

(Georg., I, 477.)

D'âme nulle et de chair avide, Don Juan, dès l'adolescence, se


prépara à l'accomplissement de sa vocation et de son rôle
légendaire. La prescience des habiles lui révéla ce qu'il devait être,
et il entra dans la carrière armé et orné de cette devise:
«Pour plaire, il faut prendre ce qui plaît à celles qui plaisent.»
A une défaillante blonde, il prit le geste de comprimer d'une main
adroite le douloureux battement d'un cœur absent;
A une autre, il prit un ironique clignement des paupières qui
donnait l'illusion de l'impertinence et qui n'était que la souffrance
d'un œil faible devant la lumière;
A une autre, il prit le geste du petit doigt levé et regardé avec
soin comme une trouvaille rare;
A une autre, il prit le joli frappement d'un pied subtilement
impatient;
A une autre, languide et pure, il prit le sourire où, comme dans
un miroir magique, on voit, avant, les contentements d'après le jeu,
et après le jeu, la réviviscence des joies du désir;
A une autre, non moins pure, mais vive et sans langueurs,
toujours agitée de mouvements pareils à ceux d'une chatte aux
heures d'orage, il prit encore un sourire, le sourire où il y a des
baisers si puissants qu'ils déconcertent le cœur des vierges;
A une autre, il prit le soupir, le long soupir brisé qui est le timide
frère du sanglot, le soupir impressionnant et qui annonce la tempête
comme un vol précipité d'oiseau;
A une autre, il prit la lente et inquiétante démarche de celles qui
sont aimées de trop d'amour;
A une autre, il prit l'amoureuse façon de dire à mi voix des riens
et de susurrer: «Il pleut», comme s'il pleuvait des anges.
Il prit des regards, tous les regards, les doux, les impérieux, les
dociles, les étonnés, les compatissants, les envieux, les fins, les fiers,
les dévorants, les foudroyants et beaucoup d'autres, parmi lesquels
le chapelet, compté grain à grain, des regards fascinateurs. Mais le
plus beau regard que prit Don Juan, rubis entre les coraux, saphir
entre les turquoises, ce fut le regard de bête traquée que lui légua,
mourante d'amour et de désespoir, une fille qu'il avait violée. Ce
regard était si touchant que nul n'y résistait, pas même la plus
farouche, et que les vœux éternels fondaient à sa lueur comme un
péché sous un rayon de grâce.

II

Don Juan fit encore une plus admirable conquête, celle d'une
âme,—une âme ingénue et fière, tendre et hautaine, d'une
séductrice douceur et d'une séductrice violence, et une âme qui ne
se connaissait pas, une âme pleine d'instinctifs désirs, une âme
délicieusement naïve.
Il s'était approché, paré de toutes ses séductions, le geste
douloureux atténué par un peu d'ironie dans l'œil et un peu de joie
sur les lèvres; sa démarche lente de créature trop aimée se
corrigeait par un fier redressement de tête, et le premier long soupir
brisé qui sortit de sa poitrine fut accompagné d'un frappement de
pied subtilement impatient,—comme pour dire: «Vous m'avez blessé
le cœur; je ne puis m'empêcher de vous aimer, mais j'en éprouve de
la colère.» Ensuite, il fit le regard de la bête traquée; ensuite, il joua
à regarder son petit doigt.
Après quelque silence, il susurra amoureusement: «Il fait beau,
ce soir»,—et tout de suite la jeune femme répondit: «C'est mon âme
que vous me demandez, Don Juan! Eh bien! prenez-la, je vous la
donne.»
Don Juan accepta l'âme délicieusement naïve et si féminine que
la soudaine amoureuse lui offrait avec sa peau, ses cheveux, ses
dents, toutes ses beautés et le parfum de tous ses arcanes,—et,
ayant joui de la soudaine amoureuse, il s'éloigna.
De l'âme, il se fit un candide et invincible manteau où il se
drapait, ainsi qu'en des plis de velours blanc,—et, orné d'une telle
âme, plus triomphant qu'un tueur de Mores, plus adoré qu'un pèlerin
de Saint-Jacques ou qu'un revenant de Palestine, il poussa ses
conquêtes jusqu'au nombre de mille et trois.
Toutes! toutes celles qui peuvent donner un plaisir nouveau, une
nuance nouvelle de joie, toutes se laissaient prendre par celui qui
avait pris à leurs sœurs tout ce qui plaît. Elles venaient au-devant de
lui, et, lui baisant les mains, faisaient leur soumission, amoureuse
peuplade vaincue déjà par l'approche du vainqueur.
Bientôt, elles se battirent à qui serait la première soumise et la
plus soumise, et, ivres d'esclavage, elles mouraient d'amour avant
d'avoir aimé.
Par les villes et dans les châteaux, et jusque parmi les bergères,
on n'entendait plus que ce cri des énamourées: «O ma chère! ô ma
chair! Il est irrésistible!»
III

Cependant, Don Juan se fanait. La sève épanouie en luxuriantes


forces retomba en pluie de feuilles sèches et, toujours aussi grand,
l'arbre n'était plus qu'une ombre.
Des tardives fleurs, Don Juan donna le dernier grain de pollen;
tant qu'il eut dans le sang une goutte de semence, il aima,—puis, ne
pouvant plus aimer, il se coucha et attendit celle qui devait venir, la
seule qu'il n'eût pas encore captée.
Et quand elle arriva, Don Juan, pour la capter, lui offrit tout ce qui
plaît, tout ce qu'il avait pris à celles qui plaisent.
—Je te donne la séduction, dit Don Juan, à toi, la laide, mes
gestes, mes regards, mes sourires, mes voix diverses, tout et même
mon manteau, qui est une âme: prends et va-t'en! Je veux revivre
ma vie par le souvenir, car je sais maintenant que la véritable vie,
c'est le souvenir.
—Revis ta vie, dit la Mort. Je reviendrai.
La Mort disparut et les Simulacres se levèrent du milieu de
l'ombre.
C'étaient de jeunes et belles femmes toutes nues et toutes
muettes, inquiètes comme des êtres à qui il manque quelque chose.
Elles se tenaient en spirale autour de Don Juan, et pendant que la
première lui mettait la main sur la poitrine, la dernière était si loin
dans les espaces qu'elle se confondait avec les étoiles.
Celle qui lui mettait la main sur la poitrine lui arracha le geste de
comprimer l'émotion d'un cœur absent;
Une autre lui reprit l'ironique cillement de ses blanches
paupières;
Une autre lui reprit la grâce de contempler l'ongle de son petit
doigt;
Une autre lui reprit l'impatience de ses pieds;
Une autre lui reprit le complexe sourire qui donne la satisfaction
avant et le désir après;
Une autre lui reprit le sourire où, comme dans une alcôve,
s'étendent des pâmoisons;
Une autre lui reprit son soupir d'oiseau peureux;
Et il fut encore dépouillé de sa lente démarche d'être qu'on aime
trop; et de sa façon amoureuse de dire: «Il pleut», comme s'il
pleuvait des anges; et du chapelet, compté grain à grain, de ses
regards: les impérieux comme les étonnés, les dociles et les
fascinateurs lui furent repris;—et la douce violée vint à son tour lui
reprendre son regard de bête traquée par l'amour et par le
désespoir.
Une autre, enfin, lui reprit son âme, l'âme délicieusement naïve
dont il s'était fait un manteau de velours blanc,—et il ne resta de
Don Juan qu'un fantôme inane, qu'un riche sans argent, qu'un
voleur sans bras, une morne larve humaine réduite à la vérité, disant
son secret!
LES FUGITIVES

Laisse la rue à ceux que leur âme importune.

ALBERT SAMAIN.

«Et pourquoi une, se disait-il, quand il y a les autres? Quel


commandement primitif me destina celle-ci, au lieu de celle-là? Je ne
serai pas l'esclave d'une chair unique; je veux que mon désir
divague, je veux le lâcher vers les inconnues par des routes
inconnues…»
Son imagination malade souffrait très réellement de la multiplicité
des femmes et parfois une fièvre d'érotisme cérébral le surexcitait à
crier, tout à fait hors de propos: «Il y en a trop! Il y en a trop!»
Il aurait voulu résumer sur des lèvres élues toute l'essence du
Féminin et la boire d'un baiser,—et l'accomplissement de son désir
néronien eût tué le Désir aussi sûrement qu'on tue les roses en
coupant le rosier et qu'on tue les sourires en tranchant la tête.
Aspirer d'une seule prise d'haleine le dernier souffle de l'Amour, le
dernier parfum de la Vie et toute sa fécondité, maîtriser la dernière
volonté de l'âme et sa dernière volupté!
Ces crises de déraison le prostraient; puis il riait de sa fantaisie
pour ne pas avoir peur de sa folie: le dévergondage s'apaisait alors
en d'innocents rêves; il jugeait son amie décidément adorable, la
seule, celle qui vaut toutes les autres, et il la louait de confirmer si
absolument, par un sourire indécis, le néant mystérieux et délicieux
de ses paroles:
«Ta magnifique inintelligence, lui disait-il, te rapproche de l'Infini;
tu fraternises avec l'Absolu, et le rien qui se meurt dans tes yeux,
pareil à la lumière d'une étoile abolie, me prouve qu'on peut à la fois
être et ne pas être…

Et le Néant m'a fait une âme comme lui.

«… Mais comprends ce que cela signifie: qu'en n'étant rien, tu es


tout,—et toutes.»
Volontiers, la pauvre amie l'eût jeté à la porte, mais elle le
craignait, et il profitait de sa peur pour lui égrener le chapelet des
fugitives.
C'était la forme seconde de sa folie.
Il disait:
«Ah! toutes celles qui sont en toi, je vais te les réciter. Je les ai
vues, je les ai prises, je les ai mises en toi: ce sont les femmes de la
rue, les femmes qui passent, les inconnues qui s'en vont, on ne sait
où elles vont, qui s'en vont par des chemins inconnus. Elles sont en
toi, mais tu n'en sais rien, et moi, le sais-je—puisque si je te touche
elles se libèrent de toi et s'en retournent vers leurs mystères. Celles
qui sont en toi vraiment n'y sont pas: c'est rêver qu'on rêve—et je
n'ai dit cela, ma chère, que par politesse, pour soustraire tout
prétexte à ta légitime jalousie.
«Franchement, tu es trop minuscule pour contenir tant de rêves
et tant de désirs. Celles que j'aime sont innombrables; je vais te les
réciter:
«Une avait la démarche sûre et nerveuse d'une chasseresse, et
quelles jambes fines et droites! Et juste ce qu'il faut de chair pour
l'harmonie de la forme, la souplesse d'une branche de frêne. Quand
elle défaille, les jours d'amour, au pied des vieux chênes
consolateurs, dans les lointaines forêts dont le soleil a peur, je ne
suis pas là, je ne serai jamais là… Ah! je meurs de désir!
«Une autre avait de si jolis cheveux couleur d'aurore et son
ventre (je le veux) était aussi blanc qu'un tapis d'asphodèles… Celle-
là non plus, jamais!
«Des yeux verts, oui, celle que je vois maintenant a des yeux
verts, des yeux de succube, des yeux de fantôme, des yeux de nuit
d'orage… Et je ne les verrai jamais s'ouvrir et fulminer dans l'ombre!
«Les autres?… Il y en a trop! il y en a trop! Les emmitouflées de
l'hiver qui ressemblent, avec leurs fourrures, à de soyeuses chèvres
de Mingrélie, ces inquiétantes bêtes qui fascinent les hommes!… Les
presque dévêtues de l'été! une agrafe, un bouton,—et la chair tiède
palpite, odorante!… Il y en a trop! il y en a trop!… Oh! ce féminin
obscur qui passe et qui s'en va, et qu'on ne touchera jamais,—et qui
s'évanouirait, si on le touchait; car son charme est d'être inconnu et
intouchable,—et si on les tenait dans ses bras, celles-là, on ne les
aimerait plus, on penserait aux autres, encore aux autres, aux
fugitives, toujours, toujours aux autres!»
Pendant que l'amie pleurait, triste et fâchée, il continuait:
«Et quand mon rêve se réaliserait, et quand je les aurais eues
toutes et même les autres, ou bien si j'avais bu sur les lèvres de
l'Unique tout le féminin, tout l'amour et toute la vie,—il resterait
encore les Impérissables. Il resterait Hélène, il resterait Salomé, il
resterait Madeleine, il resterait Ophélie—et toutes celles que les
poètes ont faites éternelles!»
Alors l'amie pleurante et fâchée riait à son tour,—et l'amant de
l'infini, le fastueux buveur d'âmes, pacifiait ses délires grandioses,
écroulé sur la chair compatissante d'une toute petite femme sans
beauté.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like