블로그 이미지
LifeisSimple

calendar

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

Notice

2012. 4. 3. 22:48 Brain Trainning/DataBase


Database 파일들의 정보를 조회하는 스크립트 입니다. 

대충 대충 필요하겠다 싶은것을 정리했습니다. 

/*

           Database file 별상태점검

                     - by Koon

*/

create proc dbo.DBA_GetDBFilesInfo

as

 

set nocount on

 

if exists (select top 1 * from sys.tables where name = 'DBA_DBFileInfo')

           truncate table DBA_DBFileInfo

else

           create table DBA_DBFileInfo (db_name nvarchar(100), db_id int, file_id int, type_desc nvarchar(60), data_space_id int, name sysname, physical_name nvarchar(260),  state_desc nvarchar(60), size int, max_size int, growth int, is_percent_growth bit)

 

insert into  DBA_DBFileInfo (db_name , db_id, file_id, type_desc, data_space_id, name, physical_name,  state_desc, size, max_size, growth, is_percent_growth)

exec sp_msforeachdb 'use ?; select db_name(), db_id(), file_id, type_desc, data_space_id, name, physical_name,  state_desc, size, max_size, growth, is_percent_growth from sys.database_files'

 

select a.db_id, a.db_name, a.file_id, a.name, a.physical_name, state_desc, convert(varchar(20), (a.size * 8 / 1024)) + 'MB' as file_size, -- (BytesOnDisk / 1024 / 1024)  as used_size,

           max_size, (case when is_percent_growth = 1 then convert(varchar(3), a.growth) + '%' else convert(varchar(20), (a.growth * 8) / 1024) + 'MB' end) as file_growth,

           convert(decimal(13, 2), (NumberReads * 1.00 / (NumberReads + NumberWrites * 1.00)) * 100) as ReadsPercent,

           convert(decimal(13, 2), (NumberWrites * 1.00 / (NumberReads + NumberWrites * 1.00)) * 100) as WritesPercent,

           NumberReads, (BytesRead / 1024 / 1024) as MBytesRead, (IoStallReadMS / 1000) as IoStallReadSec,

           NumberWrites, (BytesWritten / 1024 / 1024) as MBytesWritten, (IoStallWriteMS / 1000) as IoStallWriteSec

from DBA_DBFileInfo a

           cross apply sys.fn_virtualfilestats(a.db_id, a.file_id)

order by a.db_id, a.file_id

posted by LifeisSimple
2010. 11. 30. 11:50 Brain Trainning/DataBase
출처 : http://www.mssqltips.com/tip.asp?tip=2139

SQL Server Agent Job Management

Written By: Jeremy Kadlec -- 10/26/2010 -- read/post comments -- print -- Bookmark and Share 

Rating:  Rate 

Problem
At our organization we have been using SQL Server Agent since SQL Server 2000.  We typically setup the Job and that is about it.  If we need to make a change we do that and do not think twice about it.  On some of our servers we have hundreds of jobs, so in this circumstance, we have lost track of what many of them do.  Recently, we have been getting asked a number of questions from our management and Development team about when changes were made, scheduling options, dependencies, etc.  Can you give me any insight into how to best leverage SQL Server Agent?

Solution
SQL Server Agent has been critical to the SQL Server installations I have worked on since the SQL Server 6.5 days.  Much of the core functionality remains the same in SQL Server Agent, but new features have been added over the years which every DBA should know about and consider when they deploy new SQL Server Agent Jobs.  Here are some items to consider:

  • Naming conventions
  • Custom Categories
  • Job Notes
  • Schedules
  • Dependencies

Naming Conventions

When it comes to naming conventions, I have only seen a few companies that have put any thought into how they name their SQL Server Agent Jobs.  For the most part the job names are logical for the task they are completing, but not grouped by name or category.  DBAs end up scanning the jobs to find what they are looking for rather than being able to look at a subset of SQL Server Agent Jobs quickly and find the correct one.  If you have 50 or more jobs, using standard prefixes or custom categories (see below) should help that process.

As such, I recommend creating logical prefixes for your SQL Server Agent Jobs.  Some of these prefixes could be:

  • "Admin" or "DBA" - Prefix for DBA related Jobs
    • These could also include a subset of jobs with these secondary prefixes:
      • "Maint", "Backup", "Restore", "SSIS", etc.
    • Another aspect to job names that is important to me is the frequency.  These prefixes could be:
      • Hourly, Daily, Weekly, Monthly, Ad-Hoc, Month-End Process, etc.
    • If you pull all of this together a few examples could be:
      • Admin - Maint - Weekly - Index Rebuilds
      • Admin - Backup - Daily - System and User Defined Databases
      • Admin - SSIS - Hourly - Product Catalog Import
  • Application Name - Prefix for jobs related to an application
    • For example, "Siebel", "CRM", "Manufacturing", etc., these too could include the frequency or other beneficial categorizations to your organizations.
  • Business Process - Prefix for jobs related to a business process
    • For example, "Revenue Reports", "External Reports", "Dashboard Refresh", etc., these too could include the frequency or other beneficial categorizations to your organizations.

Another aspect of naming conventions that I have seen benefit one organization is adding a prefix "zDisabledToDelete" with the date for deletion to indicate when the job should be deleted.  This gives you the benefit of sorting the job at the end of the list and knowing when the job is intended to be deleted.  For example, a disabled job could be named "zDisabledToDelete_12312010_Admin-SSIS-Daily-Export".


Custom Categories

Along the same lines of naming conventions is custom job categories.  In some organizations, they organize their jobs by custom category rather than by name.  Both of these techniques are not mutually exclusive.  You could have a custom category setup along with a naming convention.  In either circumstance, select a process, be consistent and stick with it.

For information on how to setup a custom category in SQL Server 2000 and 2008, check out this tip from Tim Ford:


Job Notes

Job notes.  What job notes?  Did you know you have the option to record job notes for each of your SQL Server Agent Jobs?  Unfortunately, I see more Jobs with blank job notes than anything meaningful.

In SQL Server 2000, the job notes section was short to say the least.  With SQL Server 2005 and 2008, you now have a much larger text box to store relevant and important job notes.  Why don't you take advantage of the opportunity and include this type of information:

  • Description
  • Start Date
  • General Schedule
  • Revision History
    • Just a simple note with who, when and what was changed in the job will garner applause from me.
  • Point of Contact
    • IT
    • Business Unit
  • Dependencies
    • Jobs, Databases, SSIS Packages, XML feeds, FTP sites, etc.

Here is a screen shot of a sample set of job notes in SQL Server 2008:

SQL Server Agent Job Notes

*** NOTE *** - Press CTRL + ENTER to insert blank lines in the Description interface shown above.

Depending on the job type, you also have the ability to record notes in the individual job steps.  For Transact-SQL script (T-SQL) you can use two dashes ("--") to comment one line of code or use a forward slash followed by one or more asterisks in conjunction with one or more asterisks followed by a forward slash i.e. (/*** Code here ***/) to comment out more than one line of code.

 With these options to record notes in your SQL Server Agent Jobs, please take advantage of them for the following reasons:

  • Have a general history for the job without having to check production change logs.
  • Know who to get in touch with if a job fails without having to send a mass email or individually ask team members.
  • Ability to have multiple team members troubleshoot job issues.

Schedules

I have the unfortunate story to share where I found a SQL Server with hundreds of duplicate jobs, one for each day of the week, database, etc.  For example, there were seven full backup jobs, one for each day of the week.  There were import and export processes that also had one job per day.  Another set of maintenance jobs for each type of maintenance (DBCC CHECKDB, UPDATE STATISTICS, DBCC UPDATEUSAGE, etc.) times the number of databases.  The folks at this organization did not know any better and were trying to do the right thing.  They just had a lot of SQL Server Agent Jobs.

With this being said, one job can have multiple schedules.  For example, one job can run at 8:00 AM, 10:00 AM and 5:00 PM.  This is accomplished with separate schedules, see below.

In addition, you can setup one job to run on multiple days at the same time in one job schedule.  See the screen shot below as a point of reference.

Check out all of the scheduling options (one time, daily, weekly, monthly, hourly, one time a day, etc.) before you schedule your next job to ensure the least number of schedules are created.


Dependencies

Another item I have run into is a complex set of jobs that need to run across a number of different SQL Server instances in a serial manner.  In this circumstance, the jobs were setup to run based on time delays assuming the previous job completed successfully.  This worked for the company for a period of time because there were only a dozen or so jobs and there was plenty of time to complete the jobs with 15 minute gaps.  At times jobs would fail or run over the 15 minute grace period, so they would troubleshoot it and move on.

As there business grew, so did the data and the corresponding complexity.  They also began losing processing time to meet business needs in additional time zones.  So the processing windows shrunk quickly and trying to manage more jobs became even more complex.

In this circumstance, be sure to check out the msdb.dbo.sp_start_job system stored procedure in conjunction with Linked Servers.  With a properly configured Linked Server, you can call the msdb.dbo.sp_start_job system stored procedure across the Linked Server as the final job step of the current job to start the next job.  This should help with running a process when the preceding job failed and also prevent trying to time balance the jobs to prevent overlap.

Next Steps

  • Evaluate your current processes to manage your SQL Server Agent Jobs.
  • Consider some of the options outlined in this tip and build a set of processes that make sense for your organization.
  • Once you have your processes in place, work through the process one SQL Server instance at a time to ensure all of the jobs meet your standard.
  • Do you have other SQL Server Agent best practices you follow?  Please let us know in the comments section (see above) for this tip.
  • Stay tuned for some additional SQL Server Agent tips to help you benefit from implementing one or more of the processes listed in this tip.
  • Until then, check out the published SQL Server Agent tips.  They are a wealth of information to get you up to speed on SQL Server Agent.
Readers Who Read This Tip Also Read
posted by LifeisSimple
2010. 11. 29. 17:53 Brain Trainning/DataBase
출처 : http://www.mssqltips.com/tip.asp?tip=1921

Best practices for working with read only databases in SQL Server

Written By: Atif Shehzad -- 1/14/2010 -- read/post comments -- print -- Bookmark and Share 

Rating:  Rate 

Problem

Databases whose architecture or data is not required to be updated should be considered to be set as READ ONLY databases. For one of my archival databases, I am looking to make it READ ONLY and would like to know what steps I should take.  In this tip I go over some best practices before setting a database to READ ONLY.

Solution

In this section we would go through best practices for preparing a database for READ ONLY status. Databases can be set to READ ONLY mode and back using T-SQL and SSMS.  For our testing we will use the sample database AdventureWorks to carry out all operations.

Preparing a database for READ ONLY state

Once a database is changed to READ ONLY nothing will change in your database.  So based on this, certain changes should be made to optimize the performance of a READ ONLY database.

Consider these facts:

  • Statistics will not be automatically updated (nor required) and you would not be able to update statistics of a READ ONLY database
  • READ ONLY databases will not shrink automatically or manually
  • You will not be able to create indexes
  • You will not be able to defragment indexes of a READ ONLY database
  • READ ONLY databases will not allow you to add any extended properties on any of its objects
  • Permissions may not be edited and users may not be added or removed from a READ ONLY database

So it is required to complete such tasks before we set the database to READ ONLY mode. The following script provides an outline to start with. You may add or remove certain steps in the script according to your specific requirements. The script assumes that your database is in the FULL recovery mode and also you have a prior full backup as a base for transactional log backups. If that is not the case then you may skip step 1 and 2 in the following script

Script 1: Prepare database for READ ONLY status

Use AdventureWorks
GO
-- Step 1. Assuming that DB has recovery model FULL and has a prior full backup. 
--Create transactional log backup
BACKUP LOG AdventureWorks TO disk = 'D:\AdventureWorksTLog'
GO
-- Step 2. Assuming that DB has recovery model FULL. Set Recovery model to Simple
ALTER DATABASE AdventureWorks SET RECOVERY SIMPLE
GO
-- Step 3. Shrink the database
DBCC SHRINKDATABASE (AdventureWorks, TRUNCATEONLY)
GO
-- Step 4. Create/rebuild/reorganize indexes where required
-- Step 5. De-fragment indexes where required
-- Step 6. Add extended properties for database if required
EXEC [AdventureWorks].sys.sp_addextendedproperty @name=N'Purpose ', 
@value=N'DB made READ ONLY for testing purpose.' 
GO
-- Step 7. Modify permissions if required and add/remove users appropriately
-- Step 8. Update all statistics
EXEC sp_updatestats
GO

 


Set database to READ ONLY status

Setting your database to READ ONLY itself is quite simple, but demands prior considerations and preparation. After completing tasks in script 1, we are ready to change the status of AdventureWorks to READ ONLY. This task may be accomplished through the system stored procedure sp_dboption or through and ALTER DATABASEcommand.

Using ALTER DATABASE command is recommended as sp_dboption may be excluded from newer versions of SQL Server.

The following script would set AdventureWorks to READ ONLY state

Script 2: Set AdventureWorks to READ ONLY status

-- Set DB to READ ONLY status through ALTER DATABASE
ALTER DATABASE AdventureWorks SET READ_ONLY
GO

The same task may be performed through SSMS. Right click on the database and go to properties. Click on Options in left panel and scroll to 'state' related options at end. Here you can manage the READ ONLY property of the database.

Set database READ ONLY through SSMS

 


Verify the READ ONLY state of database

As a database changes to READ ONLY through SSMS, the color of the database folder in SSMS will instantly change and it would look as follows. If the database is changed to READ ONLY through T-SQL then a refresh of your databases may be required to show the color change in SSMS.

Changed Color of READ ONLY DB in SSMS

You can also verify the READ ONLY property of a database using this T-SQL,

Script 3: Verify that DB is READ ONLY or not

-- A value of 1 corresponds to READ ONLY state
SELECT name, is_read_only 
FROM sys.databases 
WHERE name = 'AdventureWorks'
GO

Working with backups of READ ONLY databases

There are couple of important points that should be kept in view while working with backups of READ ONLY databases.

  • You can create any type of backup (full, differential, log) of a database in READ only state. However considering the READ ONLY state you may want to have a different backup plan than that of a READ WRITE database. Consider using simple recovery mode along with only full backups.
  • A full backup of READ ONLY database would be recovered as a READ ONLY database. Recovered databases may be changed to READ WRITE mode later.
  • A full backup of READ WRITE database over a READ ONLY database would make the target database READ WRITE, so you would need to change the state of the database again.

Performance benefits of READ ONLY state

  • As there would be no data modifications in a READ ONLY state, SQL Server would not have to bother with locks.
  • You can create additional indexes to optimize data retrieval without worrying about degradation of data modifications and index maintenance.
  • You can copy data and log files of a READ ONLY database while the database is online

Change READ ONLY database to READ WRITE

If there is a need to change a READ ONLY database to READ WRITE this task can be performed both through T-SQL or SSMS.

Script 4: Change state of READ ONLY database to READ WRITE

-- Set DB to READ WRITE status through ALTER DATABASE
ALTER DATABASE AdventureWorks SET READ_WRITE
GO

SSMS may also be used for changing database state in the same way as mentioned in first image above. If task is performed through T-SQL then you will need to refresh the databases in SSMS to see the color  change of the database folder back to normal.

Next Steps

  • Do not forget to disable application features that previously were being used to update the database
  • Click here to read more about updating statistics in SQL Server databases or read this tip
  • Click here to read more about index maintenance operations
  • Click here to read more about shrinking database
  • Click here to read more about using extended properties on SQL Server objects
  • Click here to read more about working with recovery models for SQL Server databases or read this tip
Readers Who Read This Tip Also Read
posted by LifeisSimple
2010. 11. 23. 02:06 Brain Trainning/DataBase

use master

go

 

 

declare @srvName varchar(100)

 

declare curSrv cursor fast_forward for

                  SELECT

                  srv.name

                  -- ISNULL(ll.remote_name, N'') AS [RemoteUser],

                  -- CAST(ll.uses_self_credential AS bit) AS [Impersonate],

                  -- ll.modify_date AS [DateLastModified]

                  FROM sys.servers AS srv

                                   INNER JOIN sys.linked_logins ll ON ll.server_id=CAST(srv.server_id AS int)

                                   LEFT OUTER JOIN sys.server_principals sp ON ll.local_principal_id = sp.principal_id

                  WHERE ll.remote_name = 'Account_Name'  -- 기타 등등 조건 추가 (원하는 녀석으로)

                  group by srv.name

 

open curSrv

 

fetch next from curSrv

                  into @srvName

                 

while @@FETCH_STATUS = 0

begin

                 

                  EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname = @srvName, @locallogin = NULL , @useself = N'False',

                                   @rmtuser = N'NewUser', @rmtpassword = N'NewPassword'

                 

                  fetch next from curSrv

                                   into @srvName

end

 

close curSrv

deallocate curSrv

posted by LifeisSimple
2010. 11. 8. 16:33 Brain Trainning/DataBase

How to centralize your SQL Server Event Logs.

By Geoff Albin, 2010/11/08

Total article views: 238 | Views in the last 30 days: 238

How to centralize your SQL Server Event Logs

SQL Server running on Windows provides a wonderful feature many DBA's overlook. It's called the Event Log. SQL Server will automatically record all sorts of info about what SQL is doing into the Event Log. I am sure we have all read the Event Log looking for things like why a server rebooted unexpectedly or to try to figure out why something is not working. But there is a lot of info in there that we may overlook. Especially since most of it does not really apply to SQL.

There are many modern day tools that will make this function very easy, but they typically cost a lot of money. Not that I am opposed to spending the boss's money, but sometimes the boss will not let me. So I came up with a process that will get some important info about SQL into my hands without having to spend time on every single instance setting up individual alerts and SQL Agent jobs to find this information.

Step 1 - create the database

You will need a database we can use to create a table to place the logs. I like to call it DBA.

-----------------------------------
USE [MASTER]
GO
-----------------------------------
CREATE DATABASE [DBA]
GO
-----------------------------------

Step 2 - Create the Table

This will be the table that holds the event logs. I like to call it EventLogStaging. Go into SSMS and open a New Query . Copy and paste the code below into the SSMS window.

USE [DBA]
GO
-----------------------------------
SET ANSI_NULLS ON
GO
-----------------------------------
SET QUOTED_IDENTIFIER ON
GO
-----------------------------------
CREATE TABLE [dbo].[EventLogStaging](
 
[RecordNumber] [int] NOT NULL,
 
[Category] [int] NOT NULL,
 
[ComputerName] [nvarchar](250) NOT NULL,
 
[EventCode] [int] NOT NULL,
 
[EventType] [int] NOT NULL,
 
[Message] [nvarchar](4000) NULL,
 
[SourceName] [nvarchar](250) NOT NULL,
 
[TimeGenerated] [datetime] NULL,
 
[TimeWritten] [datetime] NOT NULL
) ON [PRIMARY]
-----------------------------------
GO

Now you have a table

Step 3 - Create a VB script as EventLog2DB.vbs

Copy and paste the code below into a new Notepad file. Save it as EventLog2DB.vbs. Remember that in Windows, you will have to choose "Save as type: All Files" or it will become a text file. Copy it over to the SQL Server you are going to monitor. (Remember the location where you copied it to.) I always have an E: drive on my servers, so I create a directory called E:\Monitor and I run EventLog2DB.vbs from there. If you do not have an E: drive, use C:\Monitor.

strComputer = "."
Set objConn = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.Recordset")
objConn
.Open "Provider=SQLOLEDB.1;Data Source=.;Initial Catalog=DBA;Integrated Security=SSPI"
objRS
.CursorLocation = 3
objRS
.Open "SELECT * FROM EventLogStaging" , objConn, 3, 3
' Get to the Event Log
Set objWMIService = GetObject("winmgmts:" _
 
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
' get the events we want
query
= "Select * from __InstanceCreationEvent" _
 
& " " & "where TargetInstance isa 'Win32_NTLogEvent'" _
 
& " " & "and TargetInstance.Logfile = 'Application'" _
 
& " " & "and (TargetInstance.EventType = 1 or TargetInstance.EventType = 2)" _
 
& " " & "and (TargetInstance.SourceName like 'MSSQL%')"
' get ready to insert into our DBA table
Set colMonitoredEvents = objWMIService.ExecNotificationQuery(query)
Do
 
Set objLatestEvent = colMonitoredEvents.NextEvent
 objRS
.AddNew
 objRS
("RecordNumber") = objLatestEvent.TargetInstance.RecordNumber
 objRS
("Category") = objLatestEvent.TargetInstance.Category
 objRS
("ComputerName") = objLatestEvent.TargetInstance.ComputerName
 objRS
("EventCode") = objLatestEvent.TargetInstance.EventCode
 objRS
("EventType") = objLatestEvent.TargetInstance.EventType
 objRS
("Message") = objLatestEvent.TargetInstance.Message
 objRS
("SourceName") = objLatestEvent.TargetInstance.SourceName
 objRS
("TimeGenerated") = WMIDateStringToDate(objLatestEvent.TargetInstance.TimeGenerated)
 objRS
("TimeWritten") = WMIDateStringToDate(objLatestEvent.TargetInstance.TimeWritten)
 objRS
.Update
Loop
' if we ever finish, we close cleanly.
objRS
.Close
objConn
.Close
Set objRS = Nothing
Set objConn = Nothing
'******************************************************************************
'* This conversion is necessary because WMI uses a different date/time format *
'******************************************************************************
Function WMIDateStringToDate(dtmInstallDate)
 WMIDateStringToDate
= CDate(Mid(dtmInstallDate, 5, 2) & "/" & _
 Mid
(dtmInstallDate, 7, 2) & "/" & Left(dtmInstallDate, 4) _
 
& " " & Mid (dtmInstallDate, 9, 2) & ":" & _
 Mid
(dtmInstallDate, 11, 2) & ":" & Mid(dtmInstallDate, _
 
13, 2))
End Function

Hey, what's this VB script doing to my system? Is it safe?

Let's break it down.

strComputer = "."
Set objConn = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.Recordset")
objConn
.Open "Provider=SQLOLEDB.1;Data Source=.;Initial Catalog=DBA;Integrated Security=SSPI"

Here we are simply making a connection to the local instance on the server where this script is run from. You can see that we are using integrated security and the database we created called DBA. The strComputer = "." is a variable that we pass later on in the script.

objRS.CursorLocation = 3
objRS
.Open "SELECT * FROM EventLogStaging" , objConn, 3, 3
' Get to the Event Log
Set objWMIService = GetObject("winmgmts:" _
 
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

The connection we made on the previous step is connecting the table we created earlier called EventLogStaging. It is also going to connect to the local Event Log service.

' get the events we want 
query
= "Select * from __InstanceCreationEvent" _
 
& " " & "where TargetInstance isa 'Win32_NTLogEvent'" _
 
& " " & "and TargetInstance.Logfile = 'Application'" _
 
& " " & "and (TargetInstance.EventType = 1 or TargetInstance.EventType = 2)" _
 
& " " & "and (TargetInstance.SourceName like 'MSSQL%')"

Here you see we connect to and read from the Event Log. We are only interested in the Application log. That is where SQL likes to put its info. We are only interested in event types of 1 and 2. Those are warnings and errors. The source name of MSSQL% will guarantee that we get the event logs of all the instances installed.

' get ready to insert into our DBA table 
Set colMonitoredEvents = objWMIService.ExecNotificationQuery(query)
Do
 
Set objLatestEvent = colMonitoredEvents.NextEvent
 objRS
.AddNew
 objRS
("RecordNumber") = objLatestEvent.TargetInstance.RecordNumber
 objRS
("Category") = objLatestEvent.TargetInstance.Category
 objRS
("ComputerName") = objLatestEvent.TargetInstance.ComputerName
 objRS
("EventCode") = objLatestEvent.TargetInstance.EventCode
 objRS
("EventType") = objLatestEvent.TargetInstance.EventType
 objRS
("Message") = objLatestEvent.TargetInstance.Message
 objRS
("SourceName") = objLatestEvent.TargetInstance.SourceName
 objRS
("TimeGenerated") = WMIDateStringToDate(objLatestEvent.TargetInstance.TimeGenerated)
 objRS
("TimeWritten") = WMIDateStringToDate(objLatestEvent.TargetInstance.TimeWritten)
 objRS
.Update
Loop

Here you see a Loop. All the loop is doing is reading the event log with the selected criteria that we described (Application, errors and warnings, etc...) and are being inserted into the EventLogStaging table.

This will loop forever and every time something comes into the Windows Event Log, it will automatically be inserted in our EventLogStaging table.

' if we ever finish, we close cleanly.
objRS
.Close
objConn
.Close
Set objRS = Nothing
Set objConn = Nothing
'******************************************************************************
'* This conversion is necessary because WMI uses a different date/time format *
'******************************************************************************
Function WMIDateStringToDate(dtmInstallDate)
 WMIDateStringToDate
= CDate(Mid(dtmInstallDate, 5, 2) & "/" & _
 Mid
(dtmInstallDate, 7, 2) & "/" & Left(dtmInstallDate, 4) _
 
& " " & Mid (dtmInstallDate, 9, 2) & ":" & _
 Mid
(dtmInstallDate, 11, 2) & ":" & Mid(dtmInstallDate, _
 
13, 2))
End Function

The rest of the code just ensures we close the database connection cleanly if we ever exit the process and does some date and time conversion.

I have run this script at several locations for the last 10 years. It was written originally for a Windows 2000 and SQL 2000 server. The amount of memory that is consumed by the csript.exe process is always less than 5,000K. Even with a server with only 2 GB of ram, it's not too much to worry about. Currently it is running on a Windows 2008 R2 x64 server with SQL 2008 R2 x64.

Step 4 - Create the SQL agent job to insert records in real time.

Pay attention to the line that says @command=N'cscript "E:\Monitor\EventLog2DB.vbs"',
That location E:\Monitor is where I placed the VB script we made. You can put yours wherever you want, but change that line to where you put it. Like C:\Monitor.

Also, just in case you do not run your SQL Server in mixed mode authentication, you will have to change the line that says@owner_login_name=N'sa', to a user that can run the job.

Open another New Query window and copy and paste the code below into your window.

USE [msdb]
GO
------------------------------------------------------
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
------------------------------------------------------
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
------------------------------------------------------
END
------------------------------------------------------
DECLARE @jobId BINARY(16)
EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'Monitor Event Log',
 @enabled
=1,
 @notify_level_eventlog
=0,
 @notify_level_email
=0,
 @notify_level_netsend
=0,
 @notify_level_page
=0,
 @delete_level
=0,
 @description
=N'No description available.',
 @category_name
=N'[Uncategorized (Local)]',
@owner_login_name=N'sa', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
------------------------------------------------------
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'always running',
 @step_id
=1,
 @cmdexec_success_code
=0,
 @on_success_action
=1,
 @on_success_step_id
=0,
 @on_fail_action
=2,
 @on_fail_step_id
=0,
 @retry_attempts
=0,
 @retry_interval
=0,
 @os_run_priority
=0, @subsystem=N'CmdExec',
@command=N'cscript "E:\Monitor\EventLog2DB.vbs"',
 @flags
=0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'always',
 @enabled
=1,
 @freq_type
=64,
 @freq_interval
=0,
 @freq_subday_type
=0,
 @freq_subday_interval
=0,
 @freq_relative_interval
=0,
 @freq_recurrence_factor
=0,
 @active_start_date
=20100831,
 @active_end_date
=99991231,
 @active_start_time
=0,
 @active_end_time
=235959
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'check every 1 minute',
 @enabled
=1,
 @freq_type
=4,
 @freq_interval
=1,
 @freq_subday_type
=4,
 @freq_subday_interval
=1,
 @freq_relative_interval
=0,
 @freq_recurrence_factor
=0,
 @active_start_date
=20100901,
 @active_end_date
=99991231,
 @active_start_time
=0,
 @active_end_time
=235959
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback
:
 
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave
:
---------------------------------------------
GO

What it creates is a new SQL Server Agent job called Monitor Event Log. It is set to start every time the SQL Agent starts and every 1 minute after that. Of course, every minute the SQL Agent Job sees the previous job still running, it will just skip it. Basically, we want our little VB script to always be running. And this job will do just that.

Step 5 - Test that the events are being inserted.

Open SSMS and run a query on the instance you are monitoring. Copy and paste the code into your window.

raiserror ('working great',16,1) with log

The 'raiserror' command will write an event to the Windows Application log.

Then check if the event was written. Copy and paste this into another New Query window.

SELECT * FROM [DBA].[dbo].[EventLogStaging]
order by TimeWritten desc

You should see the event 'working great' in the results window.

Well, so it's working. Great! Now I have another place to see event log info. So why do I really care about that? Let's not forget about another feature SQL has had for many years called "SQL Server event forwarding". Consider that you might have 50 instances of SQL under your watchful eye. With a quick adjustment to the SQL Server Agent properties, you can forward SQL events from the Event log to where this job and VB script script are running.


Now I have a table with ALL my events in one place. I have used this method on over 150 instances forwarding their events to a central monitor server.
In my next article, I will describe how I create triggers and Stored Procedures to notify me via email and pager when events occur that need my attention.

By Geoff Albin, 2010/11/08

Total article views: 238 | Views in the last 30 days: 238

posted by LifeisSimple
2010. 10. 16. 23:41 Brain Trainning/DataBase

SQLdiag는 콘솔 응용 프로그램 또는 서비스로 실행할 수 있는 범용 진단 정보 수집 유틸리티입니다. SQLdiag를 사용하여 SQL Server 및 기타 서버 유형에서 로그 및 데이터 파일을 수집할 수 있으며 이러한 파일을 사용하여 지속적으로 서버를 모니터링하거나 특정 서버 문제를 해결할 수 있습니다. SQLdiag는 Microsoft 고객 지원 서비스에서 진단 정보를 빠르고 간편하게 수집할 수 있도록 지원하는 유틸리티입니다.

ms162833.note(ko-kr,SQL.105).gif참고:
SQL Server 2005부터 SQLdiag 유틸리티가 획기적으로 바뀌었습니다. 이 유틸리티의 명령줄 인수는 SQL Server 2000과 호환되지 않습니다. 이 유틸리티는 변경될 수 있으며 해당 명령줄 인수나 동작을 사용하는 응용 프로그램 또는 스크립트의 경우 후속 릴리스에서 제대로 작동하지 않을 수 있습니다.

SQLdiag에서는 다음과 같은 진단 정보를 수집할 수 있습니다.

  • Windows 성능 로그
  • Windows 이벤트 로그
  • SQL Server 프로파일러 추적 정보
  • SQL Server 차단 정보
  • SQL Server 구성 정보

SQLDiag.xml 구성 파일을 편집하여 SQLdiag에서 수집할 정보 유형을 지정할 수 있습니다. 이에 대해서는 다음 섹션에서 설명합니다.

구문

sqldiag 
     { [/?] }
     |
     { [/I configuration_file]
       [/O output_folder_path]
       [/P support_folder_path]
       [/N output_folder_management_option]
              [/M machine1 [ machine2 machineN] | @machinelistfile]
       [/C file_compression_type]
              [/B [+]start_time]
       [/E [+]stop_time]
       [/A SQLdiag_application_name]
       [/T { tcp [ ,port ] | np | lpc | via } ]
       [/Q] [/G] [/R] [/U] [/L] [/X] }
     |
     { [START | STOP | STOP_ABORT] }
     |
     { [START | STOP | STOP_ABORT] /A SQLdiag_application_name }
인수

/?

사용법 정보를 표시합니다.

/Iconfiguration_file

SQLdiag에서 사용할 구성 파일을 설정합니다. 기본적으로 /I는 SQLDiag.Xml로 설정되어 있습니다.

/Ooutput_folder_path

SQLdiag 출력을 지정된 폴더로 리디렉션합니다. /O 옵션을 지정하지 않으면 SQLdiag 출력이 SQLdiag 시작 폴더의 SQLDIAG라는 하위 폴더에 기록됩니다. SQLDIAG 폴더가 없으면 SQLdiag에서 이 폴더를 만듭니다.

ms162833.note(ko-kr,SQL.105).gif참고:
출력 폴더 위치는 /P로 지정할 수 있는 지원 폴더 위치에 대해 상대적입니다. 완전히 다른 출력 폴더 위치를 설정하려면 /O에 ���해 전체 디렉터리 경로를 지정합니다.

/Psupport_folder_path

지원 폴더 경로를 설정합니다. 기본적으로 /P는 SQLdiag 실행 파일이 있는 폴더로 설정됩니다. 지원 폴더에는 XML 구성 파일, Transact-SQL 스크립트 및 진단 정보를 수집하는 동안 유틸리티에서 사용하는 기타 파일을 비롯한 SQLdiag 지원 파일이 있습니다. 이 옵션을 사용하여 대체 지원 파일 경로를 지정하면 SQLdiag는 지정한 폴더에 없는 경우 필요한 지원 파일을 자동으로 복사합니다.

ms162833.note(ko-kr,SQL.105).gif참고:
현재 폴더를 지원 경로로 설정하려면 다음과 같이 명령줄에서 %cd%를 지정합니다.

SQLDIAG /P %cd%

/Noutput_folder_management_option

SQLdiag가 시작될 때 출력 폴더를 덮어쓸 것인지 또는 이름을 바꿀 것인지 설정합니다. 사용 가능한 옵션은 다음과 같습니다.

1 = 출력 폴더를 덮어씁니다(기본값).

2 = SQLdiag가 시작될 때 출력 폴더의 이름을 SQLDIAG_00001, SQLDIAG_00002 등으로 바꿉니다. 현재 출력 폴더의 이름을 바꾼 다음 SQLdiag는 기본 출력 폴더 SQLDIAG에 출력을 씁니다.

ms162833.note(ko-kr,SQL.105).gif참고:
SQLdiag는 시작할 때 현재 출력 폴더에 출력을 추가하지 않습니다. 대신 기본 출력 폴더를 덮어쓰거나(옵션 1) 폴더의 이름을 바꾼 다음(옵션 2) SQLDIAG라는 새 기본 출력 폴더에 출력을 씁니다.

/Mmachine1 [ machine2machineN] | @machinelistfile

구성 파일에 지정된 컴퓨터를 재정의합니다. 기본적으로 구성 파일은 SQLDiag.Xml이거나 /I 매개 변수를 사용하여 설정됩니다. 둘 이상의 컴퓨터를 지정할 경우 각 컴퓨터 이름을 공백으로 구분하십시오.

@machinelistfile을 사용하면 구성 파일에 저장할 컴퓨터 목록 파일 이름이 지정됩니다.

/Cfile_compression_type

SQLdiag 출력 폴더 파일에서 사용되는 파일 압축 유형을 설정합니다. 사용 가능한 옵션은 다음과 같습니다.

0 = 없음(기본값)

1 = NTFS 압축을 사용합니다.

/B [+]start_time

진단 데이터 수집 시작 날짜와 시간을 다음 형식으로 지정합니다.

YYYYMMDD_HH:MM:SS

시간은 24시간제 표시법으로 지정합니다. 예를 들어 오후 2시는 14:00:00으로 지정해야 합니다.

날짜 없이 HH:MM:SS에 +를 사용하여 현재 날짜와 시간에 대한 상대 시간을 지정할 수 있습니다. 예를 들어 /B +02:00:00으로 지정하면 SQLdiag에서는 2시간 후부터 정보 수집을 시작합니다.

+와 지정한 start_time 사이에 공백을 넣지 마십시오.

지정한 시작 시간이 과거일 경우 SQLdiag에서 강제로 시작 날짜를 변경하여 시작 날짜와 시간을 미래 시간으로 설정합니다. 예를 들어 현재 시간이 08:00:00인데 /B 01:00:00이라고 지정하면 SQLdiag에서 강제로 시작 날짜를 다음 날로 변경합니다.

SQLdiag는 유틸리티를 실행하는 컴퓨터의 현지 시간을 사용합니다.

/E [+]stop_time

진단 데이터 수집 종료 날짜와 시간을 다음 형식으로 지정합니다.

YYYYMMDD_HH:MM:SS

시간은 24시간제 표시법으로 지정합니다. 예를 들어 오후 2시는 14:00:00으로 지정해야 합니다.

날짜 없이 HH:MM:SS에 +를 사용하여 현재 날짜와 시간에 대한 상대 시간을 지정할 수 있습니다. 예를 들어 시작 시간과 종료 시간을 /B +02:00:00 /E +03:00:00으로 지정하면 SQLdiag에서는 2시간 후부터 정보 수집을 시작하고 3시간 동안 정보를 수집한 다음 중지하고 끝냅니다. /B를 지정하지 않으면 SQLdiag에서 즉시 진단 정보 수집을 시작하고 /E로 지정된 날짜와 시간에 종료합니다.

+와 지정한 start_time 또는 end_time 사이에 공백을 넣지 마십시오.

SQLdiag는 유틸리티를 실행하는 컴퓨터의 현지 시간을 사용합니다.

/A SQLdiag_application_name

동일한 SQL Server 인스턴스에 대해 여러 SQLdiag 유틸리티 인스턴스를 실행할 수 있도록 합니다.

각 SQLdiag_application_name은 서로 다른 SQLdiag 인스턴스를 식별합니다. SQLdiag_application_name 인스턴스와 SQL Server 인스턴스 이름은 전혀 관계가 없습니다.

SQLdiag_application_name은 특정 SQLdiag 서비스 인스턴스를 시작하거나 중지하는 데 사용할 수 있습니다.

예를 들면 다음과 같습니다.

SQLDIAG START /A SQLdiag_application_name

또한 /R 옵션과 함께 사용하여 특정 SQLdiag 인스턴스를 서비스로 등록할 수 있습니다. 예를 들면 다음과 같습니다.

SQLDIAG /R /ASQLdiag_application_name

ms162833.note(ko-kr,SQL.105).gif참고:
SQLdiag는 SQLdiag_application_name에 대해 지정한 인스턴스 이름 앞에 DIAG$를 자동으로 붙입니다. SQLdiag를 서비스로 등록하는 경우 이를 통해 구분이 가능한 서비스 이름이 제공됩니다.

/T { tcp [ ,port ] | np | lpc | via }

지정된 프로토콜을 사용하여 SQL Server 인스턴스에 연결합니다.

tcp [, port]

TCP/IP(Transmission Control Protocol/Internet Protocol)입니다. 필요에 따라 연결을 위한 포트 번호를 지정할 수 있습니다.

np

명명된 파이프입니다. 기본적으로 SQL Server의 기본 인스턴스는 명명된 인스턴스에 대한 명명된 파이프 \\.\pipe\sql\query 및 \\.\pipe\MSSQL$<instancename>\sql\query에서 수신합니다. 대체 파이프 이름을 사용하여 SQL Server 인스턴스에 연결할 수는 없습니다.

lpc

로컬 프로시저 호출입니다. 이 공유 메모리 프로토콜은 클라이언트가 같은 컴퓨터에 있는 SQL Server 인스턴스에 연결하는 경우 사용할 수 있습니다.

via

VIA(Virtual Interface Adapter) 프로토콜입니다. VIA 하드웨어에 사용됩니다. VIA 사용 방법에 대한 자세한 내용은 하드웨어 공급업체에 문의하십시오.

ms162833.note(ko-kr,SQL.105).gif참고:
VIA 프로토콜은 더 이상 사용되지 않습니다. Microsoft SQL Server의 이후 버전에서는 이 기능이 제거됩니다. 새 개발 작업에서는 이 기능을 사용하지 않도록 하고, 현재 이 기능을 사용하는 응용 프로그램은 수정하십시오.

프로토콜에 대한 자세한 내용은 네트워크 프로토콜 선택을 참조하십시오.

/Q

자동 모드에서 SQLdiag를 실행합니다. /Q는 암호 프롬프트와 같은 모든 프롬프트를 표시하지 않습니다.

/G

일반 모드에서 SQLdiag를 실행합니다. /G를 지정하면 시작 시 SQLdiag에서 SQL Server 연결을 확인하거나 사용자가 sysadmin 고정 서버 역할의 멤버인지 확인하지 않습니다. 대신 SQLdiag는 사용자에게 각각의 요청된 진단 정보를 수집할 수 있는 권한이 있는지 여부를 Windows를 통해 확인합니다.

/G를 지정하지 않으면 SQLdiag에서 사용자가 Windows Administrators 그룹의 멤버인지 확인하고 Administrators 그룹 멤버가 아닐 경우 SQL Server 진단 정보를 수집하지 않습니다.

/R

SQLdiag를 서비스로 등록합니다. SQLdiag를 서비스로 등록할 때 지정하는 모든 명령줄 인수는 나중에 서비스를 실행할 때 사용할 수 있도록 보관됩니다.

SQLdiag를 서비스로 등록할 경우 기본 서비스 이름은 SQLDIAG입니다. /A 인수를 사용하여 서비스 이름을 변경할 수 있습니다.

다음과 같이 START 명령줄 인수를 사용하여 서비스를 시작할 수 있습니다.

SQLDIAG START

다음과 같이 net start 명령을 사용하여 서비스를 시작할 수도 있습니다.

net start SQLDIAG

/U

서비스로 등록된 SQLdiag의 등록을 취소합니다.

명명된 SQLdiag 인스턴스의 등록을 취소하는 경우에는 /A 인수도 사용합니다.

/L

각각 /B 또는 /E 인수를 사용하여 시작 시간이나 종료 시간도 지정한 경우 SQLdiag가 연속 모드로 실행됩니다. 예약된 종료로 인해 진단 정보 수집이 중지되면 SQLdiag가 자동으로 다시 시작됩니다. 예를 들어 /E 또는/X 인수를 사용하면 종료됩니다.

ms162833.note(ko-kr,SQL.105).gif참고:
/B 및 /E 명령줄 인수를 사용하여 시작 시간이나 종료 시간을 지정하지 않는 경우 SQLdiag는 /L 인수를 무시합니다.

/L은 서비스 모드를 나타내는 인수가 아닙니다. SQLdiag를 서비스로 실행할 때 /L을 사용하려면 해당 서비스를 등록할 때 명령줄에서 /L을 지정해야 합니다.

/X

스냅숏 모드에서 SQLdiag를 실행합니다. SQLdiag는 구성된 모든 진단 정보에 대해 스냅숏을 만들고 자동으로 종료됩니다.

START | STOP | STOP_ABORT

SQLdiag 서비스를 시작하거나 중지합니다. STOP_ABORT는 현재 수행하고 있는 진단 정보 수집을 완료하지 않고 가능한 빨리 서비스를 강제 종료합니다.

이러한 서비스 제어 인수를 사용할 때는 명령줄에서 첫 번째 인수로 사용해야 합니다. 예를 들면 다음과 같습니다.

SQLDIAG START

명명된 SQLdiag 인스턴스를 지정하는 /A 인수만 STARTSTOP 또는 STOP_ABORT와 함께 사용하여 특정 SQLdiag 서비스 인스턴스를 제어할 수 있습니다. 예를 들면 다음과 같습니다.

SQLDIAG START /ASQLdiag_application_name

보안 요구 사항

/G 명령줄 인수를 지정하여 일반 모드에서 SQLdiag를 실행하지 않을 경우 SQLdiag를 실행하는 사용자는 Windows Administrators 그룹의 멤버이면서 SQL Server sysadmin 고정 서버 역할의 멤버여야 합니다. 기본적으로SQLdiag에서는 Windows 인증을 사용하여 SQL Server에 연결하지만 SQL Server 인증도 지원합니다.

성능 고려 사항

SQLdiag를 실행할 때 성능에 미치는 영향은 수집하도록 구성한 진단 데이터 형식에 따라 다릅니다. 예를 들어 SQL Server 프로파일러 추적 정보를 수집하도록 SQLdiag를 구성한 경우 추적할 이벤트 클래스를 많이 선택할수록 서버 성능에 더 많은 영향을 줍니다.

SQLdiag를 실행할 때 성능에 미치는 영향은 구성한 진단 정보를 개별적으로 수집할 때 드는 노력을 모두 합한 것과 거의 같습니다. 예를 들어 SQLdiag로 추적 정보를 수집할 경우 SQL Server 프로파일러를 사용하여 해당 정보를 수집하는 것과 동등한 성능 영향을 받게 됩니다. SQLdiag 사용으로 인해 성능에 미치는 영향은 매우 적습니다.

필요한 디스크 공간

SQLdiag에서는 여러 가지 진단 정보를 수집할 수 있으므로 SQLdiag를 실행하는 데 필요한 디스크 공간은 그에 따라 다릅니다. 수집하는 진단 정보의 양은 서버에서 처리하는 작업의 성격과 양에 따라 다르며 몇 MB부터 몇 GB에 이르기까지 매우 다양합니다.

구성 파일

시작 시 SQLdiag에서는 지정된 구성 파일 및 명령줄 인수를 읽습니다. 사용자는 구성 파일에 SQLdiag가 수집할 진단 정보 유형을 지정합니다. 기본적으로 SQLdiag에서는 SQLDiag.Xml 구성 파일을 사용합니다. 이 구성 파일은 해당 도구가 실행될 때마다 추출되며 SQLdiag 유틸리티 시작 폴더에 있습니다. 이 구성 파일은 XML 스키마인 SQLDiag_schema.xsd를 사용하며 이 스키마 또한 SQLdiag를 실행할 때마다 실행 파일에서 유틸리티 시작 디렉터리로 추출됩니다.

구성 파일 편집

SQLDiag.Xml을 복사 및 편집하여 SQLdiag에서 수집하는 진단 데이터 형식을 변경할 수 있습니다. 구성 파일을 편집할 때는 항상 Management Studio와 같은 XML 스키마에 대해 구성 파일의 유효성을 검사할 수 있는 XML 편집기를 사용하십시오. 직접 SQLDiag.Xml을 편집해서는 안 됩니다. 대신 SQLDiag.Xml을 복사하고 새 파일 이름으로 바꿔 같은 폴더에 저장합니다. 그런 다음 이 파일을 편집하고 /I 인수를 사용하여 SQLdiag로 전달합니다.

SQLdiag를 서비스로 실행할 때 구성 파일 편집

이미 SQLdiag를 서비스로 실행한 경우 구성 파일을 편집하려면 /U 명령줄 인수를 지정하여 SQLDIAG 서비스의 등록을 취소한 다음 /R 명령줄 인수를 사용하여 이 서비스를 다시 등록합니다. 서비스의 등록을 취소하고 다시 등록하면 Windows 레지스트리에 캐시된 이전 구성 정보가 제거됩니다.

출력 폴더

/O 인수를 사용하여 출력 폴더를 지정하지 않으면 SQLdiag가 SQLdiag 시작 폴더에 SQLDIAG라는 하위 폴더를 만듭니다. SQL Server 프로파일러와 같이 추적 정보의 양이 많은 진단 정보를 수집하는 경우 로컬 드라이브의 출력 폴더에 요청된 진단 정보 출력을 저장할 수 있는 충분한 공간이 있는지 확인합니다.

SQLdiag를 다시 시작하면 출력 폴더의 내용을 덮어씁니다. 이 문제를 방지하려면 명령줄에서 /N 2를 지정합니다.

데이터 수집 프로세스

SQLdiag가 시작되면 SQLDiag.Xml에 지정된 진단 데이터를 수집하는 데 필요한 초기화 검사가 수행됩니다. 이 프로세스는 몇 초 정도 걸릴 수 있습니다. SQLdiag를 콘솔 응용 프로그램으로 실행하는 경우 진단 데이터 수집을 시작하면 SQLdiag에서 수집을 시작했으며 Ctrl+C를 눌러 중지할 수 있음을 알리는 메시지가 표시됩니다. SQLdiag를 서비스로 실행하는 경우 이와 비슷한 메시지가 Windows 이벤트 로그에 기록됩니다.

SQLdiag를 사용하여 재현할 수 있는 문제를 진단하는 경우 이 메시지가 표시된 다음에 서버에서 해당 문제를 재현합니다.

SQLdiag에서는 대부분의 진단 데이터를 병렬로 수집합니다. Windows 성능 로그 및 이벤트 로그에서 정보를 수집하는 경우를 제외하고 모든 진단 정보는 SQL Server sqlcmd 유틸리티나 Windows 명령 처리기와 같은 도구에 연결하여 수집합니다. SQLdiag에서는 컴퓨터당 작업자 스레드를 하나씩 사용하여 이러한 도구의 진단 데이터 수집을 모니터링하므로 동시에 여러 도구가 완료되기까지 기다려야 하는 경우도 있습니다. 수집이 진행되는 동안SQLdiag는 각 진단의 출력을 출력 폴더로 라우팅합니다.

데이터 수집 중지

SQLdiag에서 진단 데이터를 수집하기 시작하면 사용자가 직접 중지하거나 지정한 시간에 중지되도록 구성한 경우를 제외하고 계속해서 데이터를 수집합니다. /E 인수를 사용하여 중지 시간을 지정하거나 /X 인수를 사용하여SQLdiag를 스냅숏 모드로 실행하면 지정한 시간에 중지되도록 SQLdiag를 구성할 수 있습니다.

SQLdiag가 중지되면 시작했던 모든 진단이 중지됩니다. 예를 들어 수집 중인 SQL Server 프로파일러 추적이 중지되고 실행 중인 Transact-SQL 스크립트 실행이 중지되며 데이터를 수집하는 동안 발생한 모든 하위 프로세스가 중지됩니다. 진단 데이터 수집이 완료되면 SQLdiag가 종료됩니다.

ms162833.note(ko-kr,SQL.105).gif참고:
SQLdiag 서비스를 일시 중지하는 작업은 지원되지 않습니다. SQLdiag 서비스를 일시 중지하면 일시 중지했을 때 수집하던 진단 정보 수집을 완료한 다음 중지됩니다. SQLdiag를 중지한 다음 다시 시작하면 응용 프로그램이 다시 시작되며 출력 폴더가 덮어쓰여집니다. 출력 폴더를 덮어쓰지 않으려면 명령줄에서 /N 2를 지정합니다.

콘솔 응용 프로그램으로 실행하는 SQLdiag를 중지하려면

SQLdiag를 콘솔 응용 프로그램으로 실행하는 경우 SQLdiag가 실행 중인 콘솔 창에서 Ctrl+C를 눌러 중지할 수 있습니다. Ctrl+C를 누르면 SQLDiag 데이터 수집이 종료되며 프로세스가 종료될 때까지 몇 분 정도 기다려야 한다는 메시지가 콘솔 창에 표시됩니다.

Ctrl+C를 두 번 눌러 모든 자식 진단 프로세스를 종료하고 즉시 응용 프로그램을 종료합니다.

서비스로 실행하는 SQLdiag를 중지하려면

SQLdiag를 서비스로 실행하는 경우 SQLdiag 시작 폴더에서 SQLDiag STOP을 실행하여 중지합니다.

동일한 컴퓨터에서 여러 SQLdiag 인스턴스를 실행하는 경우 서비스를 중지할 때 명령줄에서 SQLdiag 인스턴스 이름을 전달할 수도 있습니다. 예를 들어 Instance1이라는 SQLdiag 인스턴스를 중지하려면 다음 구문을 사용합니다.

SQLDIAG STOP /A Instance1
ms162833.note(ko-kr,SQL.105).gif참고:
/A는 STARTSTOP 또는 STOP_ABORT와 함께 사용할 수 있는 유일한 명령줄 인수입니다. 서비스 제어 동사 중 하나로 명명된 SQLdiag 인스턴스를 지정해야 하는 경우 이전 구문 예에서와 같이 명령줄에서 제어 동사 뒤에/A를 지정합니다. 제어 동사를 사용할 때는 명령줄에서 첫 번째 인수로 사용해야 합니다.

가능한 빨리 서비스를 중지하려면 유틸리티 시작 폴더에서 SQLDIAG STOP_ABORT를 실행합니다. 이 명령을 사용하면 현재 수행 중인 진단 정보 수집이 완료되기를 기다리지 않고 중단합니다.

ms162833.note(ko-kr,SQL.105).gif참고:
SQLDiag STOP 또는 SQLDIAG STOP_ABORT를 사용하여 SQLdiag 서비스를 중지할 수 있습니다. SQLdiag 또는 기타 SQL Server 서비스를 중지할 때는 Windows 서비스 콘솔을 사용하지 마십시오.

SQLdiag 자동 시작 및 중지

지정한 시간에 진단 데이터 수집을 자동으로 시작하고 중지하려면 24시간제 표시법을 사용하여 /Bstart_time 및 /Estop_time 인수를 사용합니다. 예를 들어 계속해서 02:00:00 경에 나타나는 문제를 해결하려면 01:00:00에 자동으로 진단 데이터 수집을 시작하여 03:00:00에 자동으로 중지하도록 SQLdiag를 구성할 수 있습니다. 시작 시간과 중지 시간은 각각 /B 및 /E 인수를 사용하여 지정합니다. 24시간제 표시법을 사용하여 정확한 시작 및 중지 날짜와 시간을 YYYYMMDD_HH:MM:SS 형식으로 지정합니다. 현재를 기준으로 상대적인 시작 시간이나 중지 시간을 지정하려면 다음 예에서와 같이 시작 및 중지 시간 앞에 +를 붙이고 날짜 부분(YYYYMMDD_)을 생략합니다. 그러면 SQLdiag는 1시간 후부터 정보 수집을 시작하여 3시간 동안 정보를 수집한 다음 중지하고 종료합니다.

sqldiag /B +01:00:00 /E +03:00:00

상대적인 start_time을 지정하면 현재 날짜와 시간에 대한 상대 시간에 SQLdiag가 시작됩니다. 상대적인 end_time을 지정하면 지정한 start_time에 대한 상대 시간에 SQLdiag가 종료됩니다. 지정한 시작 및 종료 날짜와 시간이 과거인 경우 SQLdiag에서 시작 날짜와 시간이 미래가 되도록 시작 날짜를 강제로 변경합니다.

이는 선택하는 시작 및 종료 날짜에 중요한 영향을 줍니다. 다음 예를 살펴 보십시오.

sqldiag /B +01:00:00 /E 08:30:00

현재 시간이 08:00일 경우 실제로 진단 정보 수집을 시작하기 전에 종료 시간이 지났습니다. 이러한 경우 SQLDiag에서 자동으로 시작 및 종료 날짜를 다음 날로 조정하기 때문에 이 예에서 진단 정보 수집은 오늘 09:00에 시작되어(+를 사용하여 상대 시작 시간 지정) 다음날 아침 08:30까지 계속됩니다.

일일 진단 정보를 수집하는 SQLdiag 중지 및 다시 시작

수동으로 SQLdiag를 시작하고 중지할 필요 없이 지정한 진단 정보를 매일 수집하려면 /L 인수를 사용합니다. /L 인수를 사용하면 예약된 종료 후에 자동으로 다시 시작하여 SQLdiag가 계속해서 실행됩니다. /L을 지정한 경우SQLdiag가 /E 인수로 지정한 종료 시간에 도달해서 중지되거나 /X 인수를 사용하여 스냅숏 모드에서 실행되고 있기 때문에 중지되면 SQLdiag가 종료되는 대신 다시 시작됩니다.

다음 예에서는 연속 모드에서 SQLdiag를 실행하여 03:00:00부터 05:00:00까지 진단 데이터를 수집한 후 자동으로 다시 시작하도록 지정합니다.

sqldiag /B 03:00:00 /E 05:00:00 /L

다음 예에서는 연속 모드에서 SQLdiag를 실행하여 03:00:00에 진단 데이터 스냅숏을 만든 후 자동으로 다시 시작하도록 지정합니다.

sqldiag /B 03:00:00 /X /L
SQLdiag를 서비스로 실행

SQLdiag를 사용하여 장시간 진단 데이터를 수집하면서 SQLdiag를 실행 중인 컴퓨터에서 로그아웃해야 할 수도 있는 경우 이를 서비스로 실행할 수 있습니다.

SQLDiag를 등록하여 서비스로 실행하려면

명령줄에서 /R 인수를 지정하여 SQLdiag를 등록하고 서비스로 실행할 수 있습니다. 그러면 SQLdiag가 등록되어 서비스로 실행됩니다. SQLdiag 서비스 이름은 SQLDIAG입니다. SQLDiag를 서비스로 등록할 때 명령줄에서 지정한 다른 모든 인수는 보관되어 서비스를 시작할 때 다시 사용됩니다.

기본 SQLDIAG 서비스 이름을 변경하려면 /A 명령줄 인수를 사용하여 다른 이름을 지정합니다. SQLdiag는 /A를 사용하여 지정한 모든 SQLdiag 인스턴스 이름 앞에 DIAG$를 자동으로 붙여 구분이 가능한 서비스 이름을 만듭니다.

SQLDIAG 서비스의 등록을 취소하려면

서비스의 등록을 취소하려면 /U 인수를 지정합니다. 서비스로 등록된 SQLdiag의 등록을 취소하면 서비스의 Windows 레지스트리 키도 삭제됩니다.

SQLDIAG 서비스를 시작하거나 다시 시작하려면

SQLDIAG 서비스를 시작하거나 다시 시작하려면 명령줄에서 SQLDiag START를 실행합니다.

/A 인수를 사용하여 여러 SQLdiag 인스턴스를 실행하는 경우 서비스를 시작할 때 명령줄에서 SQLdiag 인스턴스 이름을 전달할 수도 있습니다. 예를 들어 Instance1이라는 SQLdiag 인스턴스를 시작하려면 다음 구문을 사용합니다.

SQLDIAG START /A Instance1

net start 명령을 사용하여 SQLDIAG 서비스를 시작할 수도 있습니다.

SQLdiag를 다시 시작하면 현재 출력 폴더의 내용을 덮어씁니다. 이러한 문제를 방지하려면 명령줄에서 /N 2를 지정하여 유틸리티가 시작될 때 출력 폴더의 이름을 바꿉니다.

SQLdiag 서비스를 일시 중지하는 작업은 지원되지 않습니다.

여러 SQLdiag 인스턴스 실행

명령줄에서 /ASQLdiag_application_name을 지정하여 동일한 컴퓨터에서 여러 SQLdiag 인스턴스를 실행할 수 있습니다. 이는 동일한 SQL Server 인스턴스에서 동시에 다른 진단 정보 집합을 수집하는 데 유용합니다. 예를 들어 지속적으로 간단한 데이터 수집을 수행하도록 명명된 SQLdiag 인스턴스를 구성할 수 있습니다. 그런 다음 SQL Server에 특정 문제가 발생하는 경우 기본 SQLdiag 인스턴스를 실행하여 해당 문제에 대한 진단 정보를 수집하거나 Microsoft 고객 지원 서비스에서 수집을 요청한 진단 정보 집합을 수집하여 문제를 진단할 수 있습니다.

클러스터형 SQL Server 인스턴스에서 진단 데이터 수집

SQLdiag에서는 클러스터형 SQL Server 인스턴스에서 진단 데이터를 수집할 수 있습니다. 클러스터형 SQL Server 인스턴스에서 진단 정보를 수집하려면 SQLDiag.Xml 구성 파일에서 <Machine> 요소의 name 특성에 대해"."를 지정해야 하며 명령줄에서 /G 인수를 지정하면 안 됩니다. 기본적으로 구성 파일에서 name 특성에는 "."가 지정되고 /G 인수는 해제되어 있습니다. 일반적으로 클러스터형 SQL Server 인스턴스에서 정보를 수집할 때는 구성 파일을 편집하거나 명령줄 인수를 변경할 필요가 없습니다.

"."를 컴퓨터 이름으로 지정하면 SQLdiag에서는 클러스터에서 실행 중임을 감지하고 해당 클러스터에 설치된 모든 가상 SQL Server 인스턴스에서 동시에 진단 정보를 검색합니다. 컴퓨터에서 실행 중인 가상 SQL Server 인스턴스 중 하나에서만 진단 정보를 수집하려면 SQLDiag.Xml에서 <Machine> 요소의 name 특성에 해당 가상 SQL Server를 지정합니다.

ms162833.note(ko-kr,SQL.105).gif참고:
클러스터형 SQL Server 인스턴스에서 SQL Server 프로파일러 추적 정보를 수집하려면 클러스터에서 관리 공유(ADMIN$)를 설정해야 합니다.


출처 : MSDN 설명

'Brain Trainning > DataBase' 카테고리의 다른 글

Collate 쿼리... (CI_AS -> CS_AS)  (0) 2010.10.19
MNG : Backup 유지관리계획  (0) 2010.10.17
SQL Server 2008 SP2 (서비스팩2)  (0) 2010.10.04
MySQL Clustering Config  (0) 2010.09.29
MySQL Clustering on Ubuntu  (0) 2010.09.29
posted by LifeisSimple
2010. 9. 13. 15:59 Brain Trainning/DataBase
대략... Job로그 등의 삭제와
필요없는 과거 DB Backup File의 삭제


declare @DeleteDate nvarchar(50)

declare @DeleteDateTime datetime

 

set @DeleteDateTime = DateAdd(dd, -10, GetDate())

set @DeleteDate = (Select Replace(Convert(nvarchar, @DeleteDateTime, 111), '/', '-') + 'T' + Convert(nvarchar, @DeleteDateTime, 108))

 

EXECUTE master.dbo.xp_delete_file 0,N'E:\DeleteTest',N'bak',@DeleteDate,1

 

 

/*

       CleanUp Task

*/

declare @dt datetime

 

set @dt = dateadd(m,-7,getdate())

 

EXEC msdb.dbo.sp_delete_backuphistory @oldest_date=@dt

EXEC msdb.dbo.sp_purge_jobhistory @oldest_date=@dt

EXEC msdb.dbo.sp_maintplan_delete_log @oldest_time=@dt

EXEC msdb.dbo.sysmail_delete_mailitems_sp @sent_before=@dt

'Brain Trainning > DataBase' 카테고리의 다른 글

MySQL Clustering on Ubuntu  (0) 2010.09.29
MySQL Cluster 구성  (0) 2010.09.20
Brad M. McGehee SQL Presentations  (0) 2010.09.08
유용한 SQL Poster  (0) 2010.08.26
MSSQL Job(작업) 결과 조회 쿼리  (0) 2010.08.25
posted by LifeisSimple
2010. 9. 8. 11:44 Brain Trainning/DataBase
퍼나름... http://www.bradmcgehee.com/presentations/

맨땅에 해딩하면서 득도한 분의 블로그를 그대로 떳습니다. 좋은 자료가 많은 듯 합니다.

Brad M. McGehee


Presentations

Below are SQL Server presentations I have made at various user group meetings and conferences. Feel free to download for personal use.

Baton Rouge SQL Saturday

Baton Rouge, LA (August 14, 2010)

Database Maintenance Essentials (PDF, 1.4MB)
Essential DBA Skills: Best Practices Every SQL Server DBA Must Know (PDF, 1MB)

www.sqlsaturday.com

St. Louis SQL Server Users Group

St. Louis, MO (August 11, 2010)

Identifying SQL Server Performance Problems Using SQL Trace (ZIP, 800KB)
Essential DBA Skills: Introduction to Graphical Execution Plans (ZIP, 700KB)

www.stlssug.org

devLINK Technical Conference

Nashville, TN (August 5-7, 2010)

Identifying SQL Server Performance Problems Using SQL Trace (ZIP, 600KB)
How and When to ImplementIndexed Views (ZIP, 800KB)
Essential DBA Skills:Introduction to Graphical Execution Plans (ZIP, 700KB)

www.devlink.net

Hawaii .NET Users Group

Honolulu, HI (July 21, 2010)

Essential DBA Skills: Best Practices Every SQL Server Developer Should Know to Administer Their SQL Servers (PDF, 700KB)

www.hawaiidotnet.org

Pensacola SQL Saturday

Pensacola, FL (June 5, 2010)

Best Practices Every SQL Server DBA Should Know (PDF, 700KB)

www.SQLSaturday.com

IndyTechFest

Indianopolis, IN (May 22, 2010)

Database Maintenance Essentials (PDF, 500KB)

www.IndyTechFest.com

North Texas SQL Server Users Group

Dallas, TX (May 20, 2010)

How to Analyze Performance Monitor Data Using PAL (PDF, 500KB)

northtexas.sqlpass.org

24 Hours of PASS

Online Presentation (May 19, 2010)

Manage Your DBA Career: Don’t Let It Manage You (PDF, 400KB)

www.sqlpass.org

Chicago SQLSaturday

Chicago, IL (April 17, 2010)

Introduction to Graphical Execution Plans in SQL Server 2005/2008 (PDF, 1MB)
How and When to Implement Indexed Views (PDF, 900KB)

www.sqlsaturday.com

Chicago SQL Server Users Group

Chicago, IL (April 15, 2010)

How to Optimize tempdb Performance (PDF, 1MB)

chicago.sqlpass.org

Atlanta Microsoft Database Forum

Atlanta, GA (April 12, 2010)

How to Become an Exceptional DBA (PDF, 800KB)

www.atlantamdf.com

Baltimore SQL Server Users Group

Baltimore, MD (April 5, 2010)

How to Use the SQL Server 2008 Performance Data Collector to Analyze Query Performance (PDF, 600KB)

www.bssug.org

SQL Server Social Group

Cambridge, England (March 24, 2010)

How to Use the SQL Server 2008 Performance Data Collector to Analyze Query Performance (PDF, 600KB)

www.sqlsocial.com

SQL Lunch

Online Webinar (February 25, 2010)

Introduction to SQL Server Graphical Execution Plans (PDF, 1MB)

www.sqllunch.com

Pragmatic Works February SQL Server 101 Series

Online Webinar (February 23, 2010)

How to be an Exceptional DBA (PDF, 800KB)

PragmaticWorks.com

Olympia Area SQL Server Users Group

Tumwater, WA (February 11, 2010)

How and When to Use Indexed Views (PDF, 1.6MB)

olympia.sqlpass.org

Oregan SQL Develpers User Group

Portland, OR (February 10, 2010)

Introduction to Graphical Execution Plans (PDF, 1.4MB)

osql-d.sqlpass.org

Fall 2009 SQL Server Connections

Las Vegas, NV (November 12, 2009)

Free Software for SQL Server DBAs (PDF, 700KB)

www.devconnections.com

Fall 2009 SQL Server Connections

Las Vegas, NV (November 11, 2009)

Optimizing tempdb Performance (PDF, 1MB)
Introducing the SQL Server 2008 Data Collector (PDF, 800KB)

www.devconnections.com

2009 PASS Community Summit

Seattle, WA (November 4, 2009)

Identifying Performance Problems With SQL Trace (PDF, 300KB)
Demo T-SQL Files (ZIP, 5K)

www.sqlpass.org

2009 PASS Community Summit

Seattle, WA (November 3, 2009)

Mange Your DBA Career, Don’t Let it Manage You (PDF, 400K)

www.sqlpass.org

Dunedin .NET Users Group

Dunedin, New Zealand (October 22, 2009)

DBA 101: Best Practices All DBAs Should Know (PDF, 800K)

www.dot.net.nz/UserGroupPages/DunedinNET.aspx

Christchurch .NET Users Group

Christchurch, New Zealand (October 21, 2009)

How to Become an Exceptional DBA (PDF, 700K)

www.dot.net.nz/UserGroupPages/ChristchurchNET.aspx

Wellington SQL Server Users Group

Wellington, New Zealand (October 20, 2009)

Optimizing tempd Performance (PDF, 1MB)

wellington.sqlpass.org

Auckland SQL Server Users Group

Auckland, New Zealand (October 19, 2009)

DBA 101: Best Practices All DBAs Should Know (PDF, 800K)

www.aucklandsql.com

Sydney SQL Server Users Group

Sydney, Australia (October 13, 2009)

Getting the Most Out of the SQL Server 2005/2008 Profiler (PDF, 2MB)

www.sqlserver.org.au

Melbourne CBD SQL PASS Chapter

Melbourne, Australia (October 12, 2009)

Getting the Most Out of the SQL Server 2005/2008 Profiler (PDF, 2MB)

melbourne.sqlpass.org

SQL Down Under Code Camp

Wagga Wagga, Australia (October 10-11, 2009)

DBA 101: Best Practices All DBAs Should Know (PDF, 800K)
Introducing the SQL Server 2008 Data Collector (PDF, 800K)

www.sqldownunder.com/SDUCodeCamp/tabid/100/Default.aspx

Newcastle Coders Group

Newcastle, Australia (October 7, 2009)

Getting the Most Out of the SQL Server 2005/2008 Profiler (PDF, 2MB)

www.ncg.asn.au

Perth SQL Server Users Group

Perth, Australia (October 2, 2009)

Introducing the SQL Server 2008 Performance Data Collector (PDF, 800K)

www.perthsqlserver.com

Perth .NET Users Group

Perth, Australia (October 1, 2009)

Introduction to How to Interpret SQL Server Execution Plans (PDF, 800K)

www.perthdotnet.org

24 Hours of PASS

Virtual Conference (September 1, 2009)

Using SQLDiag.exe to Troubleshoot SQL Server Problems (PDF, 350KB)

www.sqlpass.org

devLINK Technical Conference

Nashville, TN (August 13-15, 2009)

Mastering the SQL Server 2008 Data Collector (PDF, 3 MB)
Getting the Most Out of the SQL Server 2005/2008 Profiler (PDF, 3MB)
Database Maintenance Optimization Strategies for the Database Professional (PDF, 2MB)

www.devlink.net



Read more: http://www.bradmcgehee.com/presentations/#ixzz0ytzWyKXI 
Under Creative Commons License: Attribution

'Brain Trainning > DataBase' 카테고리의 다른 글

MySQL Cluster 구성  (0) 2010.09.20
유지관리 - 흔적삭제  (0) 2010.09.13
유용한 SQL Poster  (0) 2010.08.26
MSSQL Job(작업) 결과 조회 쿼리  (0) 2010.08.25
Backup 용 Script  (0) 2010.08.24
posted by LifeisSimple
2010. 8. 26. 18:01 Brain Trainning/DataBase
파일 첨부

굉장한건 아니지만 책상앞에 붙여놓고 보면 좋을듯 합니다. 

'Brain Trainning > DataBase' 카테고리의 다른 글

유지관리 - 흔적삭제  (0) 2010.09.13
Brad M. McGehee SQL Presentations  (0) 2010.09.08
MSSQL Job(작업) 결과 조회 쿼리  (0) 2010.08.25
Backup 용 Script  (0) 2010.08.24
MBSA Command Line Tool  (0) 2010.08.22
posted by LifeisSimple
2010. 8. 6. 16:22 Brain Trainning/DataBase

이건 DataFile 들


create table #tmpspc (Fileid int, FileGroup int, TotalExtents int, UsedExtents int, Name sysname, FileName nchar(520))
insert #tmpspc EXEC ('dbcc showfilestats')
SELECT
db_name() as DBName,
CAST(cast(g.name as varbinary(256)) AS sysname) AS [FileGroup_Name],
s.name AS [Name],
left(s.physical_name, 1) as DriveName,
s.physical_name AS [FileName],
(tspc.TotalExtents - tspc.UsedExtents)*convert(float,64) AS [AvailableSpace],
CAST(CASE s.is_percent_growth WHEN 1 THEN s.growth ELSE s.growth*8 END AS float) AS [Growth],
CAST(CASE when s.growth=0 THEN 99 ELSE s.is_percent_growth END AS int) AS [GrowthType],
s.file_id AS [ID],
CAST(CASE s.file_id WHEN 1 THEN 1 ELSE 0 END AS bit) AS [IsPrimaryFile],
CASE when s.max_size=-1 then -1 else s.max_size * CONVERT(float,8) END AS [MaxSize],
s.size * CONVERT(float,8) AS [Size],
CAST(tspc.UsedExtents*convert(float,64) AS float) AS [UsedSpace],
CAST(case s.state when 6 then 1 else 0 end AS bit) AS [IsOffline],
s.is_read_only AS [IsReadOnly],
s.is_media_read_only AS [IsReadOnlyMedia],
s.is_sparse AS [IsSparse]
FROM
sys.filegroups AS g
INNER JOIN sys.master_files AS s ON (s.type = 0 and s.database_id = db_id() and (s.drop_lsn IS NULL)) AND (s.data_space_id=g.data_space_id)
LEFT OUTER JOIN #tmpspc tspc ON tspc.Fileid = s.file_id
ORDER BY
[FileGroup_Name] ASC,[Name] ASC

drop table #tmpspc

이건 Log 파일들

SELECT db_name() as DBName, null as [FileGroup_Name], s.name AS [Name], left(s.physical_name, 1) as DriveName, s.physical_name AS [FileName], s.size * CONVERT(float,8) - CAST(FILEPROPERTY(s.name, 'SpaceUsed') AS float)* CONVERT(float,8) as [AvailableSpace], CAST(CASE s.is_percent_growth WHEN 1 THEN s.growth ELSE s.growth*8 END AS float) AS [Growth], CAST(CASE when s.growth=0 THEN 99 ELSE s.is_percent_growth END AS int) AS [GrowthType], s.file_id AS [ID], null as IsPrimaryFile, CASE when s.max_size=-1 then -1 else s.max_size * CONVERT(float,8) END AS [MaxSize], s.size * CONVERT(float,8) AS [Size], CAST(FILEPROPERTY(s.name, 'SpaceUsed') AS float)* CONVERT(float,8) AS [UsedSpace], CAST(case s.state when 6 then 1 else 0 end AS bit) AS [IsOffline], s.is_read_only AS [IsReadOnly], s.is_media_read_only AS [IsReadOnlyMedia], s.is_sparse AS [IsSparse] FROM sys.master_files AS s WHERE (s.type = 1 and s.database_id = db_id()) ORDER BY [Name] ASC
이렇게 구경하면 됩니다. 음... 

'Brain Trainning > DataBase' 카테고리의 다른 글

버전 호환성 Upgrade 작업 후 해야할 작업  (0) 2010.08.12
SP_Helpindex2  (0) 2010.08.11
MSSQL 2008 설치 Video (Microsoft)  (0) 2010.07.23
[SSRS] Microsoft Video  (0) 2010.07.23
[SSAS] Microsoft Video  (0) 2010.07.23
posted by LifeisSimple
prev 1 2 3 next