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

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

50 477 0

Đ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

Định dạng
Số trang 50
Dung lượng 639,88 KB

Nội dung

CHAPTER 20 • SQL-DMO 770 using properties of the SQLServer object. For example, once you’ve instantiated a SQLServer object and connected it to a particular server, you can use the Databases property of the SQLServer object to retrieve a Database object referring to a particular database: Set objDatabase = objSQLServer.Databases(“Northwind”) In this example, objSQLServer is a SQLServer object. When this line of code is exe- cuted, the objDatabase object will be set to point to the Northwind database owned by the specified SQL Server. You can also use the SQLServer object to perform operations that affect an entire server. For example, you could use properties and methods of this object to drop a database, set serverwide options, or manipulate the default timeout for SQL Server logins. 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 it exposes from any COM client language. You need to set a reference to the Microsoft SQLDMO Object Library in your client code to use these objects. In the following pages, we’ll list the properties, methods, and events of the SQLServer 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 work- ing with these objects. SQLServer and SQLServer2 SQL Server 2000 has two different objects to represent the entire SQL Server. The SQL- 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 object includes all of the methods, properties, and events of the SQLServer object. In addition, 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 use the extended objects. Otherwise, you should use the earlier versions of the objects for portability. 2627ch20.qxd 8/22/00 11:13 AM Page 770 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 771 You can’t create the extended objects directly. Rather, you create the original object and then retrieve the extended object from the interface of the original object. In Visual Basic or VBA, this is as simple as assigning one object to another, as this example shows: Dim objSQLServer As SQLDMO.SQLServer2 Dim objOldSQLServer As SQLDMO.SQLServer Set objOldSQLServer = New SQLDMO.SQLServer objOldSQLServer.LoginSecure = True objOldSQLServer.Connect “HENHOUSE” On Error Resume Next Set objSQLServer = objOldSQLServer If Err = 0 Then Debug.Print objSQLServer.StartupAccount Else Debug.Print “This function is not supported.” End If Here, 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 original SQLServer object. This will work for any version of SQL Server from 6.5 forward. The code 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 assignment fails, you know that this is an older server and that the requested information isn’t available. Properties Table 20.2 lists the properties of the SQLServer and SQLServer2 objects. Although in general we’re not going to list all the properties of objects in this chapter, we wanted to give you a feel for the richness of the SQL-DMO object model. Properties with a check mark in the Extended column are available on only the SQLServer2 object. SQL-DMO OBJECT MODEL Development with SQL server PART V 2627ch20.qxd 8/22/00 11:13 AM Page 771 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 20 • SQL-DMO 772 TABLE 20.2: PROPERTIES OF THE SQLSERVER OBJECT Property Extended Description AnsiNulls True if ANSI null compatibility is enabled Application The SQL-DMO Application object AutoReConnect True if the SQLServer object automatically tries to reconnect in case of any problem AutoStart ✔ True if the SQLServerAgent starts automatically when the operating system starts BlockingTimeout Timeout interval in milliseconds when waiting for a blocked resource CodePage Code page of the server Collation ✔ Collation name for this server CommandTerminator T-SQL batch delimiter (defaults to GO) ConnectionID Unique identifier for a connected SQLServer object EnableBcp True if bulkcopy operations are enabled Hostname Network name of the client where this object is running InstanceName ✔ Name of the current instance of SQL Server IsClustered ✔ True if this server is part of a cluster Isdbcreator True if the login for this object is a member of the dbcreator role Isdiskadmin True if the login for this object is a member of the diskadmin role Isprocessadmin True if the login for this object is a member of the processadmin role Issecurityadmin True if the login for this object is a member of the securityadmin role Isserveradmin True if the login for this object is a member of the serveradmin role Issetupadmin True if the login for this object is a member of the setupadmin role Issysadmin True if the login for this object is a member of the sysadmin role Language Language ID for this server Login Username used for this connection 2627ch20.qxd 8/22/00 11:13 AM Page 772 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 773 TABLE 20.2: PROPERTIES OF THE SQLSERVER OBJECT (CONTINUED) Property Extended Description LoginSecure True if using integrated security LoginTimeout Milliseconds to wait for a connection MaxNumericPrecision Maximum precision of floating-point numbers on this server Name Name of the SQL Server NetName Network name of the server NetPacketSize Packet size used on the network by this server NextDeviceNumber Next device ID (this property is obsolete) ODBCPrefix True if error sources are returned with error messages Password Password used for this connection PID ✔ Process ID for this instance of SQL Server ProcessID Process ID for this connection ProcessInputBuffer Contents of the current input buffer ProcessOutputBuffer Contents of the current output buffer ProductLevel ✔ Product level (Beta or RTM) QueryTimeout Milliseconds to wait for query results QuotedIdentifier True if quoted identifiers are enabled on this server RegionalSetting True if SQL Server uses the client locale for dis- playing data SaLogin True if the login for this object is a member of the sysadmin role ServiceName ✔ Name of the computer where this server is running StartupAccount ✔ Name of the login account used by the SQLServerAgent service Status Status (running, paused, stopped) of the server StatusInfoRefetchInterval Sets the interval used to automatically refetch status information TranslateChar True if high-order characters are translated to the client locale TrueLogin SQL Server login used for the current connec- tion (even if integrated security was specified) SQL-DMO OBJECT MODEL Development with SQL server PART V 2627ch20.qxd 8/22/00 11:13 AM Page 773 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 20 • SQL-DMO 774 TABLE 20.2: PROPERTIES OF THE SQLSERVER OBJECT (CONTINUED) Property Extended Description TrueName The value of @@SERVERNAME from this server UserProfile Returns a series of bitflags indicating user privi- leges on the server VersionMajor Major version number VersionMinor Minor version number VersionString Complete version information Methods Table 20.3 lists the methods of the SQLServer and SQLServer2 objects. TABLE 20.3: METHODS OF THE SQLSERVER OBJECT Method Extended Description AddStartParameter Appends a startup option for this server AttachDB Attaches a database file to the current server AttachDBWithSingleFile Attaches a database stored in a single file to the current server AttachDBWithSingleFile2 ✔ Attaches a database stored in a single file to the current server BeginTransaction Starts a T-SQL transaction Close Closes the connection with the server CommandShellImmediate Executes an operating system command Executes an operating system command and returns the results CommitTransaction Commits a T-SQL transaction Connect Connects to a particular SQL Server Continue Restarts a paused server DetachDB Detaches a database from the server DetachedDBInfo ✔ Returns a result set containing informa- tion about a detached database CommandShell- ImmediateWithResults 2627ch20.qxd 8/22/00 11:13 AM Page 774 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 775 TABLE 20.3: METHODS OF THE SQLSERVER OBJECT (CONTINUED) Method Extended Description DisConnect Breaks the connection with a server EnumAccountInfo Enumerates the Windows NT accounts with access to the server EnumAvailableMedia Enumerates the drives visible to the server EnumCollations ✔ Enumerates the valid collations for this server EnumDirectories Enumerates the child directories of a directory on the server EnumErrorLogs Enumerates the error logs on the current server EnumLocks Enumerates the locks currently held on the server EnumLoginMappings Enumerates the security mappings on the current server EnumNTDomainGroups Enumerates the groups in the server’s domain EnumProcesses Enumerates the SQL Server processes on the current server EnumServerAttributes Returns a list of the properties of the current server EnumVersionInfo Returns the complete VERSIONINFO resource from the current server ExecuteImmediate Submits a T-SQL batch for immediate execution ExecuteWithResults Submits a T-SQL batch and returns the results IsDetachedPrimaryFile ✔ Returns True if a specified disk file is a primary database file IsLogin Returns True if a specified name is a valid login IsNTGroupMember Returns True if a specified user is in a specified NT group Submits a T-SQL batch and returns the results along with any messages from the server ExecuteWithResultsAnd- Messages SQL-DMO OBJECT MODEL Development with SQL server PART V 2627ch20.qxd 8/22/00 11:13 AM Page 775 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 20 • SQL-DMO 776 TABLE 20.3: METHODS OF THE SQLSERVER OBJECT (CONTINUED) Method Extended Description IsOS Returns True if this server is running on a specific operating system IsPackage Returns an integer indicating the version of SQL Server that this object refers to KillDatabase Drops a database KillProcess Terminates a process ListCollations ✔ Returns a list of all valid collation names ListCompatibilityLevels ✔ Returns a list of all valid compatibility levels ListDetachedDBFiles ✔ Returns a list of all database files refer- enced by a specified primary database file ListDetachedLogFiles ✔ Returns a list of all log files referenced by a specified primary database file ListInstalledInstances ✔ Returns a list of all named instances of SQL Server on a specified computer ListMembers Returns a list of the database roles that a particular login belongs to ListStartupProcedures Returns a list of the stored procedures that execute when the server is started Pause Pauses the server PingSQLServerVersion Returns an integer corresponding to the version of a specified server ReadBackupHeader Lists the contents of a backup device or file ReadErrorLog Returns the contents of an error log ReConnect Reconnects a disconnected server RollbackTransaction Rolls back a T-SQL batch SaveTransaction Sets a checkpoint within a T-SQL batch ServerLoginMode ✔ Returns the default login mode for the specified server Shutdown Stops the server Start Starts the server Stop Stops the server 2627ch20.qxd 8/22/00 11:13 AM Page 776 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 777 TABLE 20.3: METHODS OF THE SQLSERVER OBJECT (CONTINUED) Method Extended Description UnloadODSDLL Unloads a DLL containing extended stored procedures VerifyConnection Checks whether the current server is still connected Note that although methods and properties can both return information to the user, there are differences between them. SQL-DMO uses methods for three distinct situations: • When the SQLServer object is being told to perform an action (such as dropping a database) • When retrieving information requires supplying other information (such as checking whether a user ID belongs to a particular Windows NT group) • When the return value consists of multiple pieces of information (such as the list of all available drives on a system) These rules for distinguishing methods from properties are consistent across all the SQL-DMO objects. Events Table 20.4 lists the events that the SQLServer object makes available. All of these events are available on the original SQLServer object. There are no additional events on the extended SQLServer2 object. TABLE 20.4: EVENTS OF THE SQLSERVER OBJECT Event Occurs when… CommandSent SQL-DMO submits a T-SQL batch to be executed ConnectionBroken SQL-DMO loses its connection to the server QueryTimeout A T-SQL batch times out RemoteLoginFailed An attempt to connect to a remote server fails ServerMessage A success-with-information message is returned by the server SQL-DMO OBJECT MODEL Development with SQL server PART V 2627ch20.qxd 8/22/00 11:13 AM Page 777 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. CHAPTER 20 • SQL-DMO 778 The Configuration Object The Configuration object and its child collection of ConfigValue objects are another important part of the SQL-DMO object model. With these objects, you can retrieve or set the same configuration options for a server that you can set with the sp_configure stored procedure or the configuration options of SQL Server Enterprise Manager. The Configuration object itself has only one property, the ShowAdvancedOptions property. Setting this property to True includes the advanced configuration options in the ConfigValues collection. The Configuration object has two methods: Reconfigure- CurrentValues and ReconfigureWithOverride. Either method applies changes made to ConfigValue 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 of these objects represents a single configuration option for SQL Server. The properties of the 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 from the CurrentValue property if the CurrentValue property has been changed and the change has not yet been committed to the server) You’ll see an example of using the Configuration and ConfigValue objects later in this 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 manipulate databasewide 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 Data- base object. This is not an exhaustive listing. For the full details of these objects, refer to the SQL-DMO reference in SQL Server Books Online. 2627ch20.qxd 8/22/00 11:13 AM Page 778 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 779 TABLE 20.5: SELECTED DETAILS OF THE DATABASE OBJECT Name Type Extended Description Checkpoint M Forces a write of dirty pages back to the disk CheckTables M Checks the integrity of tables in this database CheckTablesWithResult M ✔ Checks the integrity of tables in this database and returns the results as a table CurrentCompatibility P ✔ Specifies the compatibility level of this database DboLogin P True if the current login has DBO privileges on this database ExecuteImmediate M Executes a T-SQL batch within this database IsFullTextEnabled P True if full-text searching is available for this database Name P Name of the database Permissions P A set of bitflags that indicate the privileges of the current SQL-DMO session in this database PrimaryFilePath P Path to the primary data file for this database Script M Creates a T-SQL script that re-creates this database Shrink M Reduces the space of the files holding this database SpaceAvailable P Amount of free space in the database Status 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 options that control a database. Each Database object has one DBOption object as a child. As you 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 SQL server PART V 2627ch20.qxd 8/22/00 11:13 AM Page 779 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... try the 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 = False objSQLServer.Login = “sa” objSQLServer.Password = “” objSQLServer.Connect “HENHOUSE” Debug.Print objSQLServer.TrueLogin In this case, the code attempts to log... connecting to a SQL Server, just like any other SQL- DMO procedure: Dim objDatabase As SQLDMO.Database Dim objDBFile As SQLDMO.DBFile Dim objLogFile As SQLDMO.LogFile Dim objSQLServer As SQLDMO.SQLServer ‘ Connect to the server using integrated security Set objSQLServer = New SQLDMO.SQLServer objSQLServer.LoginSecure = True objSQLServer.Connect “HENHOUSE” The next task is to instantiate the SQL- DMO database... 787 The simplest way to connect to a SQL Server is to use Windows NT integrated security You can do this by setting the LoginSecure property of the SQLServer object to True, as in the following code fragment: Dim objSQLServer As SQLDMO.SQLServer Set objSQLServer = New SQLDMO.SQLServer objSQLServer.LoginSecure = True objSQLServer.Connect “HENHOUSE” Debug.Print objSQLServer.TrueLogin This code first creates... objects and connecting to a server It also retrieves the particular database in which this table will be stored: Dim objSQLServer As SQLDMO.SQLServer Dim objDatabase As SQLDMO.Database Dim objTable As SQLDMO.Table Dim objColumn As SQLDMO.Column ‘ Connect to the server using integrated security Set objSQLServer = New SQLDMO.SQLServer objSQLServer.LoginSecure = True objSQLServer.Connect “HENHOUSE” ‘... Tables collection of the appropriate database: Dim objSQLServer As SQLDMO.SQLServer Dim objDatabase As SQLDMO.Database Dim objTable As SQLDMO.Table ‘ Connect to the server using integrated security Set objSQLServer = New SQLDMO.SQLServer objSQLServer.LoginSecure = True objSQLServer.Connect “HENHOUSE” ‘ Fetch the database of interest Set objDatabase = objSQLServer.Databases(“NewDb”) ‘ And drop the table objDatabase.Tables.Remove... property if you’re using SQL Server security Note that this 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... 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 security Set objSQLServer = New SQLDMO.SQLServer objSQLServer.LoginSecure = True objSQLServer.Connect “HENHOUSE” ‘ Create the alert and give it a name Set objAlert = New SQLDMO.Alert objAlert.Name = “Full NewDB” ‘ Associate the alert with... string) SQLNSRootType_ServerGroup SrvGrp=groupname SQLNSRootType _Server Server=servername;Trusted_Connection=Yes or Server= servername;UID=username;PWD=password SQLNSRootType_Database Server= servername;Database=databasename; Trusted_Connection=Yes or Server= servername;Database=databasename;UID=user name;PWD=password Because they use information from the user’s Registry, the SQLNSRootType_DefaultRoot and SQLNSRootType_ServerGroup... SQLDMO.Database Dim objStoredProc As SQLDMO.StoredProcedure ‘ Connect to the server using integrated security Set objSQLServer = New SQLDMO.SQLServer objSQLServer.LoginSecure = True objSQLServer.Connect “HENHOUSE” ‘ Fetch the database of interest Set objDatabase = objSQLServer.Databases(“NewDb”) PA R T V ‘ Create and name the stored procedure Set objStoredProc = New SQLDMO.StoredProcedure objStoredProc.Name... objDatabase As SQLDMO.Database Dim objDBOption As SQLDMO.DBOption ‘ Connect to the server using integrated security Set objSQLServer = New SQLDMO.SQLServer objSQLServer.LoginSecure = True objSQLServer.Connect “HENHOUSE” ‘ Fetch the database of interest Set objDatabase = objSQLServer.Databases(“Northwind”) ‘ Get the DBOption object and set it Set objDBOption = objDatabase.DBOption objDBOption.SelectIntoBulkCopy . shows: Dim objSQLServer As SQLDMO.SQLServer2 Dim objOldSQLServer As SQLDMO.SQLServer Set objOldSQLServer = New SQLDMO.SQLServer objOldSQLServer.LoginSecure. the SQLServer object to True, as in the following code fragment: Dim objSQLServer As SQLDMO.SQLServer Set objSQLServer = New SQLDMO.SQLServer objSQLServer.LoginSecure

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

TỪ KHÓA LIÊN QUAN