1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu MASTERING SQL SERVER 2000- P16 pdf

50 478 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Mastering Sql Server 2000
Thể loại tài liệu hướng dẫn
Năm xuất bản 2000
Định dạng
Số trang 50
Dung lượng 639,88 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

TABLE 20.2: PROPERTIES OF THE SQLSERVER OBJECTAutoReConnect True if the SQLServer object automatically tries to reconnect in case of any problemAutoStart ✔ True if the SQLServerAgent sta

Trang 1

using properties of the SQLServer object For example, once you’ve instantiated aSQLServer object and connected it to a particular server, you can use the Databasesproperty of the SQLServer object to retrieve a Database object referring to a particulardatabase:

Set objDatabase = objSQLServer.Databases(“Northwind”)

In this example, objSQLServer is a SQLServer object When this line of code is cuted, the objDatabase object will be set to point to the Northwind database owned

exe-by the specified SQL Server

You can also use the SQLServer object to perform operations that affect an entireserver For example, you could use properties and methods of this object to drop adatabase, set serverwide options, or manipulate the default timeout for SQL Serverlogins

NOTE All of the sample code in this chapter was written with Visual Basic Of course,because SQL-DMO is a COM server, you can use the objects, methods, and properties itexposes from any COM client language You need to set a reference to the MicrosoftSQLDMO Object Library in your client code to use these objects

In the following pages, we’ll list the properties, methods, and events of theSQLServer object These lists will give you an overview of the tasks that you can per-form directly with this object But first, we need to explain why there are two differ-ent SQLServer objects in SQL Server 2000 Later in this chapter (in the section

“Creating and Connecting a SQLServer Object”), we’ll show you an example of ing with these objects

work-SQLServer and work-SQLServer2

SQL Server 2000 has two different objects to represent the entire SQL Server The Server object can be used with both SQL Server 2000 and earlier versions of SQL Server.The SQLServer2 object can be used only with SQL Server 2000 The SQLServer2 objectincludes all of the methods, properties, and events of the SQLServer object In addition,

SQL-it exposes some new methods and properties that pertain only to SQL Server 2000

The SQLServer2 object is an example of an extended SQL-DMO object If you’re sure

that your code will be working with the latest version of SQL Server, you should usethe extended objects Otherwise, you should use the earlier versions of the objects forportability

Trang 2

You can’t create the extended objects directly Rather, you create the originalobject and then retrieve the extended object from the interface of the originalobject In Visual Basic or VBA, this is as simple as assigning one object to another,

as this example shows:

Dim objSQLServer As SQLDMO.SQLServer2Dim objOldSQLServer As SQLDMO.SQLServer

Set objOldSQLServer = New SQLDMO.SQLServerobjOldSQLServer.LoginSecure = True

objOldSQLServer.Connect “HENHOUSE”

On Error Resume NextSet objSQLServer = objOldSQLServer

If Err = 0 ThenDebug.Print objSQLServer.StartupAccountElse

Debug.Print “This function is not supported.”

End IfHere, the purpose is to retrieve the Windows NT account used by the SQLServer-Agent by querying the StartupAccount property of the SQLServer object This prop-erty is available from only the extended version of the object The code first connects

to a particular SQL Server (in this case, one named HENHOUSE) using the originalSQLServer object This will work for any version of SQL Server from 6.5 forward Thecode then assigns this object to the new extended object If the assignment succeeds,the code can retrieve the value of the StartupAccount property; if the assignmentfails, you know that this is an older server and that the requested information isn’tavailable

SQL-DMO OBJECT MODEL

Development with S QL server

P A R T

V

Trang 3

TABLE 20.2: PROPERTIES OF THE SQLSERVER OBJECT

AutoReConnect True if the SQLServer object automatically tries

to reconnect in case of any problemAutoStart ✔ True if the SQLServerAgent starts automatically

when the operating system startsBlockingTimeout Timeout interval in milliseconds when waiting

for a blocked resourceCodePage Code page of the serverCollation ✔ Collation name for this serverCommandTerminator T-SQL batch delimiter (defaults to GO)ConnectionID Unique identifier for a connected SQLServer

objectEnableBcp True if bulkcopy operations are enabledHostname Network name of the client where this object

is runningInstanceName ✔ Name of the current instance of SQL ServerIsClustered ✔ True if this server is part of a clusterIsdbcreator True if the login for this object is a member of

the dbcreator roleIsdiskadmin True if the login for this object is a member of

the diskadmin roleIsprocessadmin True if the login for this object is a member of

the processadmin roleIssecurityadmin True if the login for this object is a member of

the securityadmin roleIsserveradmin True if the login for this object is a member of

the serveradmin roleIssetupadmin True if the login for this object is a member of

the setupadmin roleIssysadmin True if the login for this object is a member of

the sysadmin roleLanguage Language ID for this serverLogin Username used for this connection

Trang 4

TABLE 20.2: PROPERTIES OF THE SQLSERVER OBJECT (CONTINUED)

MaxNumericPrecision Maximum precision of floating-point numbers

on this server

NetPacketSize Packet size used on the network by this serverNextDeviceNumber Next device ID (this property is obsolete)ODBCPrefix True if error sources are returned with error

messages

ProcessInputBuffer Contents of the current input bufferProcessOutputBuffer Contents of the current output buffer

QueryTimeout Milliseconds to wait for query resultsQuotedIdentifier True if quoted identifiers are enabled on this

serverRegionalSetting True if SQL Server uses the client locale for dis-

playing dataSaLogin True if the login for this object is a member of

the sysadmin roleServiceName ✔ Name of the computer where this server is

runningStartupAccount ✔ Name of the login account used by the

SQLServerAgent service

StatusInfoRefetchInterval Sets the interval used to automatically refetch

status informationTranslateChar True if high-order characters are translated to

the client locale

connec-tion (even if integrated security was specified)

SQL-DMO OBJECT MODEL

Development with S QL server

P A R T

V

Trang 5

TABLE 20.2: PROPERTIES OF THE SQLSERVER OBJECT (CONTINUED)

UserProfile Returns a series of bitflags indicating user

privi-leges on the server

Methods

Table 20.3 lists the methods of the SQLServer and SQLServer2 objects

TABLE 20.3: METHODS OF THE SQLSERVER OBJECT

AddStartParameter Appends a startup option for this server

serverAttachDBWithSingleFile Attaches a database stored in a single

file to the current serverAttachDBWithSingleFile2 ✔ Attaches a database stored in a single

file to the current server

CommandShellImmediate Executes an operating system command

Executes an operating system commandand returns the results

DetachedDBInfo ✔ Returns a result set containing

informa-tion about a detached databaseCommandShell-

ImmediateWithResults

Trang 6

TABLE 20.3: METHODS OF THE SQLSERVER OBJECT (CONTINUED)

with access to the serverEnumAvailableMedia Enumerates the drives visible to the

serverEnumCollations ✔ Enumerates the valid collations for this

server

directory on the server

server

the server

the current serverEnumNTDomainGroups Enumerates the groups in the server’s

domain

the current serverEnumServerAttributes Returns a list of the properties of the

current server

resource from the current server

executionExecuteWithResults Submits a T-SQL batch and returns the

results

IsDetachedPrimaryFile ✔ Returns True if a specified disk file is a

primary database file

valid loginIsNTGroupMember Returns True if a specified user is in a

specified NT group

Submits a T-SQL batch and returns theresults along with any messages fromthe server

Messages

ExecuteWithResultsAnd-SQL-DMO OBJECT MODEL

Development with S QL server

P A R T

V

Trang 7

TABLE 20.3: METHODS OF THE SQLSERVER OBJECT (CONTINUED)

a specific operating system

of SQL Server that this object refers to

ListCollations ✔ Returns a list of all valid collation namesListCompatibilityLevels ✔ Returns a list of all valid compatibility

levelsListDetachedDBFiles ✔ Returns a list of all database files refer-

enced by a specified primary database fileListDetachedLogFiles ✔ Returns a list of all log files referenced

by a specified primary database fileListInstalledInstances ✔ Returns a list of all named instances of

SQL Server on a specified computer

a particular login belongs toListStartupProcedures Returns a list of the stored procedures

that execute when the server is started

PingSQLServerVersion Returns an integer corresponding to the

version of a specified serverReadBackupHeader Lists the contents of a backup device

or file

ServerLoginMode ✔ Returns the default login mode for the

specified server

Trang 8

TABLE 20.3: METHODS OF THE SQLSERVER OBJECT (CONTINUED)

stored proceduresVerifyConnection Checks whether the current server is still

connected

Note that although methods and properties can both return information to theuser, there are differences between them SQL-DMO uses methods for three distinctsituations:

• When the SQLServer object is being told to perform an action (such as dropping

on the extended SQLServer2 object

TABLE 20.4: EVENTS OF THE SQLSERVER OBJECT

CommandSent SQL-DMO submits a T-SQL batch to be executedConnectionBroken SQL-DMO loses its connection to the serverQueryTimeout A T-SQL batch times out

RemoteLoginFailed An attempt to connect to a remote server failsServerMessage A success-with-information message is returned by the server

SQL-DMO OBJECT MODEL

Development with S QL server

P A R T

V

Trang 9

The Configuration Object

The Configuration object and its child collection of ConfigValue objects are anotherimportant part of the SQL-DMO object model With these objects, you can retrieve orset the same configuration options for a server that you can set with the sp_configurestored procedure or the configuration options of SQL Server Enterprise Manager.The Configuration object itself has only one property, the ShowAdvancedOptionsproperty Setting this property to True includes the advanced configuration options inthe ConfigValues collection The Configuration object has two methods: Reconfigure-CurrentValues and ReconfigureWithOverride Either method applies changes made toConfigValue objects back to the server The difference is that the ReconfigureWith-Override method bypasses SQL Server’s validity checking

The Configuration object has a child collection of ConfigValue objects Each ofthese objects represents a single configuration option for SQL Server The properties ofthe ConfigValue object include:

Name: The name of the option

Description: A lengthier description of the option

CurrentValue: The current value of the option

MinimumValue: The minimum allowed value of the option

MaximumValue: The maximum allowed value of the option

RunningValue: The value currently used by the server (this can differ fromthe CurrentValue property if the CurrentValue property has been changed andthe change has not yet been committed to the server)

You’ll see an example of using the Configuration and ConfigValue objects later inthis chapter in the section “Changing a Configuration Option.”

The Database Object

One of the principle objects in the SQL-DMO object model is the Database object.This object represents an entire database, and it provides a way to both manipulatedatabasewide properties and get to other objects stored in a database

Like the SQLServer object, the Database object has been extended for SQL Server 2000,

so there are both Database and Database2 object types

Table 20.5 shows some of the principle properties (P) and methods (M) of the base object This is not an exhaustive listing For the full details of these objects, refer

Data-to the SQL-DMO reference in SQL Server Books Online

Trang 10

TABLE 20.5: SELECTED DETAILS OF THE DATABASE OBJECT

Checkpoint M Forces a write of dirty pages back to the diskCheckTables M Checks the integrity of tables in this databaseCheckTablesWithResult M ✔ Checks the integrity of tables in this database

and returns the results as a tableCurrentCompatibility P ✔ Specifies the compatibility level of this databaseDboLogin P True if the current login has DBO privileges on

this databaseExecuteImmediate M Executes a T-SQL batch within this databaseIsFullTextEnabled P True if full-text searching is available for this

database

Permissions P A set of bitflags that indicate the privileges of

the current SQL-DMO session in this databasePrimaryFilePath P Path to the primary data file for this database

database

databaseSpaceAvailable P Amount of free space in the databaseStatus P Current state of the database (suspect, recovery,

loading, and so on)

You’ll see one use for the Database object in the section “Creating a Database” later

in this chapter

The DBOption Object

The DBOption object is SQL-DMO’s way of allowing you to set the overall optionsthat control a database Each Database object has one DBOption object as a child Asyou change the properties of this object, SQL Server changes the options of the refer-enced database to match The properties of this object include:

AssignmentDiag: True to enable SQL-92 null behavior

AutoClose: True to close the database when the last user exits

AutoCreateStat: True to automatically create statistics as required

SQL-DMO OBJECT MODEL

Development with S QL server

P A R T

V

Trang 11

AutoShrink: True to periodically attempt to shrink the database

AutoUpdateState: True to automatically update statistics as required

ColumnsNullByDefault: True to default newly created columns to nullable

CompareNull: True to evaluate NULL=NULL as NULL

ContactNull: True to propagate nulls in string concatenation

CursorCloseOnCommit: True to close cursors when changes are committed

DBOUseOnly: True to limit access to the database to the database owner

DefaultCursor: True to give cursors created in a batch local scope

Offline: True to place the database offline

QuoteDelimiter: True to allow quoted delimiters

ReadOnly: True to make the database read-only

RecursiveTriggers: True to allow triggers to fire other triggers

SelectIntoBulkCopy: True to allow SELECT INTO and bulkcopy operations

SingleUser: True to limit the database to one user at a time

TornPageDetection: True to force SQL Server to automatically scan fortorn pages

TruncateLogOnCheckpoint: True to truncate the log on each checkpointYou’ll see an example of using the DBOption object later in the chapter in the sec-tion “Changing a Configuration Option.”

The StoredProcedure Object

The StoredProcedure object, as you can probably guess by now, represents a singleSQL Server stored procedure This can be either a system stored procedure or a user-defined stored procedure You can use the methods and properties of this object tocreate stored procedures, set their properties, execute them, and so on

Table 20.6 shows the methods (M) and properties (P) of the StoredProcedureobject This is a complete list, because this object does not have the overwhelmingcomplexity of some of the other objects that represent larger parts of SQL Server Notethat SQL Server 2000 also exposes an extended StoredProcedure2 object

Trang 12

TABLE 20.6: DETAILS OF THE STOREDPROCEDURE OBJECT

AnsiNullsStatus M ✔ True when this stored procedure refers to a

table defined with ANSI null behavior

created

EnumDependencies M Returns a list of objects that depend on this

stored procedure or objects that this storedprocedure depends on

EnumParameters M Returns a list of parameters for this stored

procedure

this stored procedureIsDeleted P ✔ True if this stored procedure has been deleted

by another sessionListPermissions M Lists implicit and explicit permissions for a

specified userListUserPermissions M Lists explicit permissions for a specified user

QuotedIdentifierStatus P True if this stored procedure depends on a

table that uses quoted identifiers

procedureStartup P True if this stored procedure runs at server

startupSystemObject P True if this is a system stored procedure

stored procedure

SQL-DMO OBJECT MODEL

Development with S QL server

P A R T

V

Trang 13

You’ll learn more about the StoredProcedure object in the section “Creating andExecuting a Stored Procedure” later in this chapter.

The Table Object

The Table object (along with the extended Table2 object in SQL Server 2000) sents a single table within a database Other child objects of the Table object let youwork with all the other things that go into a table: columns, indexes, keys, con-straints, and so on Figure 20.1 shows the other objects that are descendants of theTable object Later in this chapter, in the section “Creating a Table,” you’ll see how touse some of these objects together in code

Checks ClusteredIndex Columns Indexes

Keys PrimaryKey Triggers

KeyColumns ReferencedColumns

DRIDefault IndexedColumns

Trang 14

TABLE 20.7: SELECTED DETAILS OF THE TABLE OBJECT

AnsiNullsStatus P ✔ True if the table uses ANSI null handlingDataSpaceUsed P Actual storage space used (in KB) for the

table’s dataEnumDependencies M Lists all the objects that this table depends on

or all the objects that depend on this tableEnumReferencedTables M Lists all the tables that this table references

via DRIEnumReferencingTables M Lists all the tables that reference this table

via DRIFullTextIndexActive P True if this table is participating in full-text

indexingFullTextPopulation M ✔ Builds the full-text index for the tableGenerateSQL M Creates a SQL statement that will create this

tableHasClusteredIndex P True if the table has a clustered index

RebuildIndexes M Rebuilds the indexes for the table

TruncateData M Deletes all rows from the table without loggingUpdateStatistics M Updates the information used for determining

optimum query plans

The Column Object

The Column object (together with the extended Column2 object) is a subsidiary ofthe Table object The Table object contains a Columns collection, which in turn con-tains one Column object for each column in the table Of course, you can use theColumns collection to iterate through all of the columns in a table:

Dim objTable as SQLDMO.TableDim objColumn As SQLDMO.Column

SQL-DMO OBJECT MODEL

Development with S QL server

P A R T

V

Trang 15

‘ Table must be instantiated before this looping code is calledFor Each objColumn in objTable.Columns

‘ Do something with each column hereNext objColumn

The Column object has more properties than methods You’ll find that this is mon as you get to the more specific objects In code, you can use properties todescribe these objects, but manipulating objects via methods is normally left to thelarger objects

com-Table 20.8 shows some of the methods (M) and properties (P) of the Columnobject

TABLE 20.8: SELECTED DETAILS OF THE COLUMN OBJECT

AlterDataType M ✔ Changes the datatype of a columnBindDefault M Associates a default with this column

ComputedText P T-SQL statement used to generate the value of

a computed column

IdentityIncrement P Increment for an identity columnIdentitySeed P Starting value for an identity columnInPrimaryKey P True if this column is part of the primary key

NumericPrecision P Precision for a numeric column

Trang 16

The Alert Object

Not all of the objects within SQL-DMO are directly related to data A good example ofone of these helper objects is the Alert object The Alert object corresponds to a singleSQL Server alert If you’re working in SQL Server Enterprise Manager, you’ll find alerts

in the Management folder under the SQLServerAgent node

NOTE Alerts are covered in more detail in Chapter 17

You can use the Alert object to create a new alert or modify the properties of anexisting alert The AddNotification method is used to associate operators (who can berepresented by Operator objects) with an alert

Table 20.9 shows some of the methods (M) and properties (P) of the Alert object

TABLE 20.9: SELECTED DETAILS OF THE ALERT OBJECT

AddNotification M Associates an operator with this alert

DatabaseName P Database that this alert monitors

EnumNotifications M Lists all the notifications for this alertJobName P Job to run when this alert is activatedMessageID P Error number that activates this alert

Severity P Error severity that activates this alert

Sample SQL-DMO Code

Now that you have some idea that SQL-DMO objects exist, and know the sort of erties and methods that they implement, it’s time to see some examples of their use

prop-SAMPLE SQL-DMO CODE

Development with S QL server

P A R T

V

Trang 17

In this section, we’ll show you seven techniques that are representative of the kinds

of things you can do with SQL-DMO:

• Creating and connecting a SQLServer object

However, before we dig into the code, we’d like to talk just a bit about why you would

write this sort of application SQL-DMO is mainly useful for two sorts of programs: general-purpose management utilities and limited-use utilities that are safe for users.Some developers make their living enhancing and extending applications like SQLServer Suppose, for example, you have an idea for a better way to design tables Per-haps instead of the standard grid metaphor, you’re envisioning a drag-and-drop envi-ronment, where you can grab predefined fields and stick them together to formtables Well, once your application has progressed to the point where the user inter-face works, you’ll need to tell SQL Server what objects to create and which properties

to assign to those objects SQL-DMO is the obvious choice for this interface to SQLServer, because it encompasses all of the things one normally needs to do with objects

On the other end of the spectrum, you might have users who occasionally need toperform an administrative task on your SQL Server Perhaps the personnel depart-ment is responsible for adding new hires in a specific job position to the list of autho-rized SQL Server operators You wouldn’t necessarily want to train your personnelpeople in the complete use of SQL Server Enterprise Manager Instead, you could useSQL-DMO in conjunction with Visual Basic to create a specialized front-end programthat could be used only for creating operators This would be easier to train your per-sonnel folks to use and safer for the server

We hope that those two illustrations, combined with the code in the rest of thechapter, will inspire you to use SQL-DMO in your own applications

Creating and Connecting a SQLServer Object

Before you can do anything else with SQL-DMO, you need to establish a connection

to the SQL Server with which you want to work This involves three basic steps:

1 Create the SQLServer object.

Trang 18

The simplest way to connect to a SQL Server is to use Windows NT integrated rity You can do this by setting the LoginSecure property of the SQLServer object toTrue, as in the following code fragment:

secu-Dim objSQLServer As SQLDMO.SQLServer

Set objSQLServer = New SQLDMO.SQLServer

objSQLServer.LoginSecure = TrueobjSQLServer.Connect “HENHOUSE”

Debug.Print objSQLServer.TrueLoginThis code first creates and instantiates (with the New keyword) a SQLServer object

The code then sets the LoginSecure property and attempts to connect with a servernamed HENHOUSE If this works, the code will print out the name of the Windows

NT security account that was used for the connection

TIP The code in this chapter uses a server named HENHOUSE for all the examples Ofcourse, you’ll need to change this to the name of your own SQL Server if you want to trythe code on your own network

You can also log in to a server by supplying a SQL Server username and password,

as in this example:

Dim objSQLServer As SQLDMO.SQLServer

Set objSQLServer = New SQLDMO.SQLServer

objSQLServer.LoginSecure = FalseobjSQLServer.Login = “sa”

account that was used (in this case, “sa”)

SAMPLE SQL-DMO CODE

Development with S QL server

P A R T

V

Trang 19

Finally, you can simplify this code by supplying the login and password directly asparameters to the Connect method Also, the LoginSecure property defaults to False,

so you can omit setting this property if you’re using SQL Server security Note thatthis won’t work if you’re using integrated security:

Dim objSQLServer As SQLDMO.SQLServer

Set objSQLServer = New SQLDMO.SQLServer

objSQLServer.Connect “HENHOUSE”, “sa”, “”

Debug.Print objSQLServer.TrueLogin

Creating a Database

One task that SQL-DMO is well suited for is the creation of new objects For example,you can use SQL-DMO to create a database entirely through code, without using the

UI or explicitly executing a CREATE DATABASE statement

The code for creating a new database starts out by defining variables and ing to a SQL Server, just like any other SQL-DMO procedure:

connect-Dim objDatabase As SQLDMO.DatabaseDim objDBFile As SQLDMO.DBFileDim objLogFile As SQLDMO.LogFileDim objSQLServer As SQLDMO.SQLServer

‘ Connect to the server using integrated securitySet objSQLServer = New SQLDMO.SQLServer

objSQLServer.LoginSecure = TrueobjSQLServer.Connect “HENHOUSE”

The next task is to instantiate the SQL-DMO database object using the New tor and give the database a name:

opera-‘ Create the database objectSet objDatabase = New SQLDMO.Database

‘ Give it a nameobjDatabase.Name = “NewDB”

At this point, the Database object exists, but SQL-DMO doesn’t yet have enoughinformation to create the database on disk The essential missing piece of information

is where to store the database You can fill this gap by creating a DBFile object (which

Trang 20

objDBFile.PhysicalName = “c:\Temp\NewDB.mdf”

‘ Size is in megabytesobjDBFile.Size = 4

WARNING In production code, you wouldn’t want to include the actual filename

in the code You might use a common dialog to prompt the user for a file location, orlook at the DBFile object belonging to the master database to determine where otherSQL Server databases on this server are stored

Once the DBFile object has been created, you can associate it with the database byadding it to the PRIMARY filegroup of the Database object There must be at least oneDBFile added to this filegroup before you can save the database You can also add asmany additional files as you’d like with the same technique

‘ Add this file to the primary filegroupobjDatabase.FileGroups(“PRIMARY”).DBFiles.Add objDBFileOptionally, you can add a log file for the database with a similar technique If youskip this step, SQL Server will use the server defaults to create a log file

‘ Now for a log fileSet objLogFile = New SQLDMO.LogFileobjLogFile.Name = “NewDBLog”

objLogFile.PhysicalName = “c:\Temp\NewDB.ldf”

objLogFile.Size = 2

‘ Add this log file to the databaseobjDatabase.TransactionLog.LogFiles.Add objLogFileOnce the database has a name and a storage location, you can cause SQL-DMO tocreate the database by adding the Database object to the server’s Databases collection:

‘ And finally add the database to the serverobjSQLServer.Databases.Add objDatabaseThat’s all you need to do to create a new database with SQL-DMO As with anyother method of creating a new database, the database will initially be a copy of the

SAMPLE SQL-DMO CODE

Development with S QL server

P A R T

V

Trang 21

model database You could use SQL-DMO to add tables, views, stored procedures, andother objects to the new database.

Changing a Configuration Option

As you already know, there are several configuration options you can set for a base, controlling such things as whether nulls are handled according to ANSI rules orwhether the database closes automatically when the last user logs out You can setthese options in code using the SQL-DMO DBOption object

data-For example, suppose you’re planning to execute a SELECT INTO query via code.Before you can do this, of course, you need to make sure that the select into/bulkcopyoption for the database is turned on Here’s the way to do that with SQL-DMO:Dim objSQLServer As SQLDMO.SQLServer

Dim objDatabase As SQLDMO.DatabaseDim objDBOption As SQLDMO.DBOption

‘ Connect to the server using integrated securitySet objSQLServer = New SQLDMO.SQLServer

objSQLServer.LoginSecure = TrueobjSQLServer.Connect “HENHOUSE”

‘ Fetch the database of interestSet objDatabase = objSQLServer.Databases(“Northwind”)

‘ Get the DBOption object and set itSet objDBOption = objDatabase.DBOptionobjDBOption.SelectIntoBulkCopy = TrueYou can use the same technique to set any of the database options; they’re allimplemented as properties of the DBOption object The section on the DBOptionobject earlier in this chapter lists all of the applicable properties

Creating a Table

Creating objects is simple with SQL-DMO In fact, you’ve already seen the generalpattern with the creation of a database:

1 Create the new object.

2 Set the object’s properties.

Trang 22

When creating a new table with SQL-DMO, this pattern repeats several times,because to create the table, you must create the columns of the table Here’s a codesample illustrating table creation It starts, of course, by defining objects and connect-ing to a server It also retrieves the particular database in which this table will be stored:

Dim objSQLServer As SQLDMO.SQLServerDim objDatabase As SQLDMO.DatabaseDim objTable As SQLDMO.TableDim objColumn As SQLDMO.Column

‘ Connect to the server using integrated securitySet objSQLServer = New SQLDMO.SQLServer

objSQLServer.LoginSecure = TrueobjSQLServer.Connect “HENHOUSE”

‘ Fetch the database of interestSet objDatabase = objSQLServer.Databases(“NewDb”)Next the code instantiates the Table object and assigns a name to it:

‘ Create the table objectSet objTable = New SQLDMO.TableobjTable.Name = “Customers”

The table is created with an empty Columns collection If you tried to add thetable to the database at this point, you’d receive an error, because a table must have atleast one column To add a column to the table, you create a Column object, set itsproperties, and add it to the Table object’s Columns collection:

‘ Add a columnSet objColumn = New SQLDMO.ColumnobjColumn.Name = “CustomerID”

objColumn.Identity = TrueobjColumn.IdentitySeed = 1objColumn.IdentityIncrement = 1objColumn.Datatype = “int”

objColumn.AllowNulls = FalseobjTable.Columns.Add objColumnOnce the Column object has been added to the collection, it’s a permanent part ofthe table You can reuse the object to add more columns to the table:

‘ Add some more columnsSet objColumn = New SQLDMO.Column

SAMPLE SQL-DMO CODE

Development with S QL server

P A R T

V

Trang 23

objColumn.Name = “CustomerName”

objColumn.Datatype = “varchar”

objColumn.Length = 50objColumn.AllowNulls = FalseobjTable.Columns.Add objColumn

Set objColumn = New SQLDMO.ColumnobjColumn.Name = “ContactName”

objColumn.Datatype = “varchar”

objColumn.Length = 50objColumn.AllowNulls = TrueobjTable.Columns.Add objColumnFinally, when you’re done creating the table and are ready to save it back to thedatabase, you add it to the Database object’s Tables collection:

‘ And add the table to the databaseobjDatabase.Tables.Add objTable

‘ Connect to the server using integrated securitySet objSQLServer = New SQLDMO.SQLServer

objSQLServer.LoginSecure = TrueobjSQLServer.Connect “HENHOUSE”

‘ Fetch the database of interestSet objDatabase = objSQLServer.Databases(“NewDb”)

‘ And drop the tableobjDatabase.Tables.Remove “Customers”, “dbo”

Note that the Remove method takes two arguments The first is the name of thetable; the second is the name of the owner of the table Supplying both arguments

Trang 24

Creating and Executing a Stored Procedure

As you can probably guess by now, creating a stored procedure involves creating anobject, setting its properties, and adding it to the appropriate collection Here’s anexample:

Dim objSQLServer As SQLDMO.SQLServerDim objDatabase As SQLDMO.DatabaseDim objStoredProc As SQLDMO.StoredProcedure

‘ Connect to the server using integrated securitySet objSQLServer = New SQLDMO.SQLServer

objSQLServer.LoginSecure = TrueobjSQLServer.Connect “HENHOUSE”

‘ Fetch the database of interestSet objDatabase = objSQLServer.Databases(“NewDb”)

‘ Create and name the stored procedureSet objStoredProc = New SQLDMO.StoredProcedureobjStoredProc.Name = “spInsertCust”

‘ Set the text of the stored procedureobjStoredProc.Text = “CREATE PROC spInsertCust “ & _

“(@CustName varchar(50), “ & _

“@ContactName varchar(50)) “ & _

“AS “ & _

“INSERT INTO Customers (CustomerName, ContactName) “ & _

“VALUES (@CustName, @ContactName)”

‘ And save itobjDatabase.StoredProcedures.Add objStoredProcNote that the Name property assigned to the stored procedure must agree with thename used in the CREATE PROC statement Also, as you can see, there’s not a greatdifference between creating a stored procedure with SQL-DMO and creating itthrough a tool such as SQL Query Analyzer Either way, you must provide the T-SQLtext of the stored procedure

SAMPLE SQL-DMO CODE

Development with S QL server

P A R T

V

Trang 25

You might expect executing a stored procedure to be a method of the StoredProcedureobject However, you’d be wrong If you need to execute a stored procedure via SQL-DMO, you use the ExecuteImmediate method of the SQLServer object:

‘ Execute the stored procedureobjDatabase.ExecuteImmediate _

“spInsertCust “”Microsoft””, “”Bill Gates”””

TI P In Visual Basic, you can use two quote marks together within a string to insert asingle quote We’ve used that technique here to pass the string parameters that thestored procedure expects Also note that you need to re-create the Customers tablebefore you can execute this stored procedure

Creating an Alert

As a final example, let’s look at creating an object that’s not directly associated withdata Even though an alert is substantially different from a table or a stored procedure,creating an alert follows the same pattern as the other examples we’ve examined:Dim objSQLServer As SQLDMO.SQLServer

Dim objAlert As SQLDMO.Alert

‘ Connect to the server using integrated securitySet objSQLServer = New SQLDMO.SQLServer

objSQLServer.LoginSecure = TrueobjSQLServer.Connect “HENHOUSE”

‘ Create the alert and give it a nameSet objAlert = New SQLDMO.AlertobjAlert.Name = “Full NewDB”

‘ Associate the alert with a particular errorobjAlert.MessageID = 9002

objAlert.DatabaseName = “NewDb”

‘ And add it to the Job ServerobjSQLServer.JobServer.Alerts.Add objAlert

Ngày đăng: 21/01/2014, 08:20

TỪ KHÓA LIÊN QUAN