Tuesday, February 14, 2012

SQL Server Jobs

PROBLEM:
You need some useful scripts for running SQL Server jobs, see status, etc.

SOLUTION:
-- Start job from script
EXEC msdb.dbo.sp_start_job N'DB_Backup';

-- List all jobs with basic info like job_id, name, etc.
SELECT * FROM msdb.dbo.sysjobs ORDER BY name

-- STOP a currently executing job
EXEC msdb.dbo.sp_stop_job N'DB_Backup' ;

-- Get job INFO on application job
EXEC msdb.dbo.sp_help_job
    @job_name = N'DB_Backup',
    @job_aspect = N'ALL' ;

-- Check run status of a job. Running = 1 means currently executing
DECLARE @job_id uniqueidentifier = 'B6371A83-93EC-4176-AB95-0423B700E880'
EXEC master.dbo.xp_sqlagent_enum_jobs 1, sa, @job_id

-- If current_execution_status=1 then RUNNING
EXEC msdb.dbo.sp_help_job  @job_id='0D823348-2DDC-4816-93EA-307D6E736437'

-- SQL Server Agent disable job
EXEC msdb.dbo.sp_update_job
    @job_name = N'DB_Backup',
    @enabled = 0 ;

-- SQL Server basic job history information for rolling month
SELECT   JobName,
         RunTime,
         Duration,
         Status,
         Server
FROM     (SELECT JobName = job_name,
                 RunTime = run_datetime,
                 Duration = SUBSTRING(run_duration,1,2) + ':' +
                            SUBSTRING(run_duration,3,2) + ':' +
                            SUBSTRING(run_duration,5,2),
                 Status = run_status,
                 Server = [server]
          FROM   (SELECT j.name AS job_name,
                         run_datetime = CONVERT(DATETIME,RTRIM(run_date)) +
                         (run_time * 9 + run_time%10000 * 6 +
                          run_time%100 * 10) / 2160000,
                         run_duration = RIGHT('000000' +
                         CONVERT(VARCHAR(6),run_duration), 6),
                         run_status = CASE run_status
                                        WHEN 0 THEN 'Failure'
                                        WHEN 1 THEN 'Success'
                                        WHEN 2 THEN 'Retry'
                                        WHEN 3 THEN 'Cancelled'
                                        WHEN 4 THEN 'Running'
                                        ELSE 'Other: ' +
                                        Convert(VARCHAR,run_status)
                                      END,
                         server
                  FROM   msdb.dbo.sysjobhistory h
                         INNER JOIN msdb.dbo.sysjobs j
                           ON h.job_id = j.job_id
                  WHERE  step_id = 0) x) z
WHERE    DATEDIFF(mm,RunTime,getdate()) < 1
ORDER BY RunTime DESC

-- SQL Server Agent detailed job information
SELECT job.name                                      AS JobName,
       job.job_id,
       job.enabled                                   AS JobEnabled,
       CONVERT(SYSNAME,SERVERPROPERTY('Servername')) AS Server,
       job.DESCRIPTION,
       job.notify_level_eventlog,
       job.notify_level_email,
       job.notify_level_page,
       job.notify_email_operator_id,
       job.date_created,
       cat.name                                      AS CategoryName,
       sch.next_run_date,
       sch.next_run_time,
       srv.last_run_outcome,
       srv.last_outcome_message,
       srv.last_run_date,
       srv.last_run_time,
       srv.last_run_duration,
       op.name                                       AS NotifyOperatorName,
       op.email_address,
       job.date_modified                             AS JobDateModified,
       ssch.name                                     AS ScheduleName,
       ssch.enabled                                  AS ScheduleEnabled,
       ssch.freq_type,
       ssch.freq_interval,
       ssch.freq_subday_interval,
       ssch.freq_subday_type,
       ssch.freq_relative_interval,
       ssch.freq_recurrence_factor,
       ssch.active_start_date,
       ssch.active_end_date,
       ssch.active_start_time,
       ssch.active_end_time,
       GETDATE()                                     AS ThisReportRunDate
FROM   msdb.dbo.sysjobs job
       INNER JOIN msdb.dbo.syscategories cat
         ON job.category_id = cat.category_id
       LEFT OUTER JOIN msdb.dbo.sysoperators op
         ON job.notify_page_operator_id = op.id
       LEFT OUTER JOIN msdb.dbo.sysjobservers srv
         ON job.job_id = srv.job_id
       LEFT OUTER JOIN msdb.dbo.sysjobschedules sch
         ON sch.job_id = job.job_id
       LEFT OUTER JOIN msdb.dbo.sysschedules ssch
         ON sch.schedule_id = ssch.schedule_id
ORDER BY JobName


If you find this solution useful, you are welcome to press one of the ads in this page.. Thanks!


Saturday, February 11, 2012

Differences between pfile and spfile


PROBLEM:
What is the differences between pfile and spfile?

SOLUTION:
Oracle provides two parameter files that you can use: PFILE or  SPFILE.

PFILE

  1. The PFILE is a text-based file usually called “initSID.ora”, meaning the file will use the ORACLE_SID you defined when you created the database.  If your SID is called TESTDB, the resulting PFILE should be called initTESTDB.ora
  2. Inside the PFILE there are database settings called parameters. These parameters help the Oracle programs know how to start.
  3. The parameters tell the Oracle programs how much memory to allocate, where to put files related to the database and where certain database files already exist.
  4. As the PFILE is text based, one can edit it in an editor like notepad or vi.
  5. Depending on which operating system you are running on, your PFILE is located by default in the ORACLE_HOME\database (usually the case on Windows) or ORACLE_HOME\dbs directory for most other platforms.
SPFILE
  1. The SPFILE is different from the PFILE in that it can not be directly edited. This is because it has a header and footer that contains binary values.
  2. Since you can not change a SPFILE directly, Oracle allows you to manage the SPFILE via the alter system command.
  3. For using an SPFILE, you can reap great benefits. It can be backed up by RMAN (Oracle’s backup and recovery software) every time a change is made or when the database is backed up, which means it’s easier to recover.
  4. SPFILES allow you to make dynamic changes to parameters that are persistent. For example
    • Alter system set db_recovery_file_dest_size=10g;
  5. If we were using SPFILES the parameter would keep the same value, even after a database restart. This means you only have to change the parameter value in one place, and that you can forget having to change it in the PFILE of the database.
  6. One of the most important benefits of the SPFILE is that Oracle has introduced many automatic tuning features into the core of the database.  Without an SPFILE, Oracle can not autotune your database.
  7. An SPFILE uses the same formatting for its file name as the PFILE, except the word spfile replaces init.  For instance, if your ORACLE_SID is TESTDB, the resulting spfile would be called spfileTESTDB.ora.
PFILE and SPFILE Backup
  1. As a DBA the main thing you need to worry about with the SPFILE and PFILES are backing them up. You can use RMAN to backup an SPFILE, or back them up yourself.
  2. PFILE is simply a text based file, which means you can copy it to another directory without affecting the Oracle instance.  This is the easiest way to backup a PFILE.
  3. To back up an SPFILE, you will first want to convert it to a PFILE. This will create a PFILE named initSID.ora in your $ORACLE_HOME/database (Windows) or $ORACLE_HOME/dbs (Linux/Unix) directory. You can do this with the following syntax
    • create pfile from spfile;
  4. In addition, you can back up the file directly to the preferred location with the command
    • create pfile=/path/to/backup.ora from spfile;
  5. If the time comes that you must put the SPFILE back into place, you can do so with this command
    • create spfile from pfile=/path/to/backup.ora
  6. You can use the V$PARAMETER dynamic view to see the current setting of the different database parameters
    • select name, value from v$parameter where name = 'control_files';
The Parameter File at Startup Time
Oracle prefers the use of an SPFILE to a PFILE.  When you startup your Oracle database, Oracle will scan the contents of your parameter directory ($ORACLE_HOME/database on Windows or the Linux directory name $ORACLE_HOME/dbs), searching in the following order:
  1. spfileSID.ora
  2. spfile.ora
  3. initSID.ora
  4. init.ora
If the directory contains none of the above, then the startup will fail.
Alternatively, you can tell Oracle where to find a PFILE if you store it in a different location.

startup pfile=/path/to/pfile/inittestdb.ora



If you find this solution useful, you are welcome to press one of the ads in this page.. Thanks!


Friday, February 3, 2012

xp_cmdshell WinRAR.exe is not recognized as an internal or external command

PROBLEM:
When running the following SQL using xp_cmdshell you get an error “xp_cmdshell WinRAR.exe is not recognized as an internal or external command”

exec xp_cmdshell 'C:\Program Files\WinRAR\WinRAR.exe a C:\db_Backup\backup.rar C:\db_Backup\BackupFolder'


SOLUTION:
Put the WinRar application path in " "

exec xp_cmdshell '"C:\Program Files\WinRAR\WinRAR.exe" a C:\db_Backup\backup.rar C:\db_Backup\BackupFolder'



If you find this solution useful, you are welcome to press one of the ads in this page.. Thanks!


Clustered index Vs. non-clustered index

PROBLEM:
When to use clustered and non-clustered indexes?

SOLUTION:

Non-clustered index
  • Data is not stored in any particular order
  • Specific data can not be retrieved quickly
  • Data pages are not linked, so sequential access needs to refer back to the index allocation map (IAM) pages
  • Since there is no clustered index, additional time is not needed to maintain the index
  • Since there is no clustered index, there is not the need for additional space to store the clustered index tree
Clustered index
  • Data is stored in order based on the clustered index key
  • Data can be retrieved quickly based on the clustered index key, if the query uses the indexed columns
  • Data pages are linked for faster sequential access
  • Additional time is needed to maintain clustered index based on INSERTS, UPDATES and DELETES
  • Additional space is needed to store clustered index tree
Read more here http://www.mssqltips.com/sqlservertip/1254/clustered-tables-vs-heap-tables


If you find this solution useful, you are welcome to press one of the ads in this page.. Thanks!

Thursday, February 2, 2012

SQL Server Unique Constraints Vs. Unique Indexes

PROBLEM:
What is the difference between SQL Server unique constraints and unique indexes?

SOLUTION:
In summary, there's no practical difference between a unique constraint and a unique index other than the fact that the unique constraint is also listed as a constraint object in the database. Since a unique constraint can't be disabled, having the status of a constraint doesn't give the unique constraint any additional behavior beyond a unique index. However, there are several index creation options that aren't available to the ALTER TABLE command that creates a unique constraint

http://msdn.microsoft.com/en-us/library/aa224827(v=sql.80).aspx


If you find this solution useful, you are welcome to press one of the ads in this page.. Thanks!


Azure Database Backup

PROBLEM:
You want to backup your Azure databases locally and also in Azure

SOLUTION:
The following steps are needed to copy Azure database to your local SQL Server 2008R2. Then you can backup it locally using a database job or manually.
First you need to allow your SQL Server to use and run xp_cmdshell

-- To allow advanced options to be changed
EXEC sp_configure 'show advanced options', 1
GO

-- To update the currently configured value for advanced options
RECONFIGURE
GO

-- To enable the feature
EXEC sp_configure 'xp_cmdshell', 1
GO

-- To update the currently configured value for this feature
RECONFIGURE
GO

Download and install SQL Azure Backup from here: http://www.red-gate.com/products/dba/sql-azure-backup
You are going to use this tool command line capabilities to automate and schedule your Azure backups with a simple stand-alone .exe
After installing Red Gate tool, use SSMS query window to run the following command. This will check if you configure xp_cmdshell and install Red Gate tool correctly

EXEC sys.xp_cmdshell 'C:\SQLAzureBackup\redgate.sqlazurebackupcommandline.exe'

This will bring the following

SQL Azure Backup v2.6.0.86
===============================================================================
Copyright (c) Red Gate Software Ltd 2011
Error: No argument for AzureServer and no default value
Back up a database from SQL Azure to SQL Server
Show Usage:

                  RedGate.SQLAzureBackupCommandLine.exe [/Help]

Copy to local sql server:
                  RedGate.SQLAzureBackupCommandLine.exe
                           /AzureServer:server /AzureDatabase:database
                           /AzureUserName:user /AzurePassword:password
                           [/CreateCopy] [/Skip] /LocalServer:server
                           /LocalDatabase:database [/LocalUserName:user]
                           [/LocalPassword:password] [/DropLocal] [/Verbose]
                           [/Help] [/Backup]

Create BACPAC file with Import/Export service CTP (Access Key):
                  RedGate.SQLAzureBackupCommandLine.exe
                           /AzureServer:server /AzureDatabase:database
                           /AzureUserName:user /AzurePassword:password
                           [/CreateCopy] /StorageAccount:name /AccessKey:key
                           /Container:container [/Filename:filename] [/Backup]

Create BACPAC file with Import/Export service CTP (Shared Access Signature):
                  RedGate.SQLAzureBackupCommandLine.exe
                           /AzureServer:server /AzureDatabase:database
                           /AzureUserName:user /AzurePassword:password
                           [/CreateCopy] /SignatureUrl:url [/Filename:filename]
                           [/Backup]

Copy to SQL Azure:
                  RedGate.SQLAzureBackupCommandLine.exe
                           /AzureServer:server /AzureDatabase:database
                           /AzureUserName:user /AzurePassword:password
                           [/CreateCopy] /LocalServer:server
                           /LocalDatabase:database [/LocalUserName:user]
                           [/LocalPassword:password] [/DropAzure] [/Restore]

  /sk:key,       /AccessKey:key          Primary or secondary access key
  /ad:database,  /AzureDatabase:database Database name to backup
  /ap:password,  /AzurePassword:password Azure password
  /as:server,    /AzureServer:server     Azure server
  /au:user,      /AzureUserName:user     Azure username
  /ba,           /Backup                 Do a backup
  /sc:container, /Container:container    Container where file will be placed
  /cc,           /CreateCopy             Ensure db transactional consistentency
  /da,           /DropAzure              Drop SQL Azure database if it exists
  /dl,           /DropLocal              Drop local database if it exists
  /sf:filename,  /Filename:filename      Filename to be created
  /?,            /Help                   Show usage
  /ld:database,  /LocalDatabase:database Database to be created
  /lp:password,  /LocalPassword:password Local password
  /ls:server,    /LocalServer:server     Local server
  /lu:user,      /LocalUserName:user     Local username for sql authentication
  /re,           /Restore                Do a restore
  /su:url,       /SignatureUrl:url       Shared access signature url
  /s,            /Skip                   Skip objects that fail to be copied
  /sa:name,      /StorageAccount:name    Backup to azure blob storage account
  /v,            /Verbose                Show verbose output


In SSMS query window or inside database backup job, use the following command to make local copy of SQL Azure database

EXEC sys.xp_cmdshell 'C:\SQLAzureBackup\redgate.sqlazurebackupcommandline.exe /AzureServer:MyAzureServerName.database.windows.net /AzureDatabase:MyDatabaseName /AzureUserName:MyUser /AzurePassword:MyPass /LocalServer:MyLocalServerName /LocalDatabase:MyDatabaseName /DropLocal'

Use the following command to make database backup in Azure (BACPAC file)

EXEC sys.xp_cmdshell 'C:\SQLAzureBackup\redgate.sqlazurebackupcommandline.exe /AzureServer:MyAzureServerName.database.windows.net /AzureDatabase:MyDatabaseName /AzureUserName:MyUser /AzurePassword:MyPass /Container:db-backup /Filename:MyDatabaseName /Backup /StorageAccount:MyStorageAccount /AccessKey:MyAccessKey'

To see you Azure database backups, download and install Azure Storage Explorer from here http://azurestorageexplorer.codeplex.com


If you find this solution useful, you are welcome to press one of the ads in this page.. Thanks!