Thursday, 14 April 2011

Database Maintenance 2

Database Management

The items I listed back in the Database Maintenance Checklist are pretty standard. All necessary to keep a server healthy. How can we improve our efficiency and take the DBA role to the next level however?

Automate test restores

Restoring data can be scheduled by script and SQL Agent Jobs easily. Providing capacity is not an issue restores can be scheduled to a test environment out of core hours.

Configure Alerts

SQL can send emails on job failures and a wide range of configurable events warning of systems events. In addition to this I personally like to configure emails for Blocking Queries, Long Running queries and Server Restarts/Failovers.

Monitor Trends

Monitor the daily growth of backups, databases, data files or even tables. This can be done into a tools database and stored on server with a relatively small overhead.
Leaving this running will provide you with accurate figures for capacity planning.

Indexes 

Periodically review database indexes. Identifying and removing duplicated and unused indexes will save space and reduce the overhead of maintaining them. Similarly running scripts or the Database Tuning Advisor may help identify new indexes that are needed.

Index maintenance jobs may hide an inappropriate index e.g one that quickly fragments. Recording the index fragmentation level before running index maintenance can help identify this. Another use for my tools database, a collection of scripts I have on each machine.




Wednesday, 13 April 2011

osql & sqlcmd

Osql has long been deprecated, but it still exists on those pesky sql 2000 servers...


osql

sqlcmd

osql usage :

osql –e –q”SELECT column FROM table”

osql -Uusername -Ppassword -Sservername -iC:\script.sql -oc:\output.txt

sqlcmd usage :

sqlcmd –e –q”SELECT column FROM table”

sqlcmd -Uusername -Ppassword -Sservername -iC:\script.sql -oc:\output.txt

parameters

-e Use Trusted Connection (windows Authentication)
-u User name
-p Password
-s Server name
-i Script name
-q Query
-o Output file
-n remove numbering


parameters

as osql parameters , with new additions including -
-b batch abort
-f Codepage
-u Unicode output
-v Pass Variables



To Get values out from osql , use the EXIT command like this -
C:\>osql -e -n -q "EXIT (SELECT 47)"

47

Or in a batch file like this...

osql -e -n -q "EXIT (SELECT COUNT(*) FROM sysobjects)"
SET SqlObjectCount=%ErrorLevel%
ECHO %SqlObjectCount%

To return values out from sqlcmd , use the EXIT command like this -
C:\>sqlcmd -Usa -Ppassword -q"EXIT(SELECT 101)"

101

Or in a batch file like this...

sqlcmd -Usa -Ppassword -q "EXIT (SELECT COUNT(*) FROM sysobjects)"
SET SqlObjectCount=%ErrorLevel%
ECHO %SqlObjectCount%


To Pass parameters in to OSQL, build a sql script file on the fly, and load it ...

SET currentobject=table1
ECHO EXIT(SET NOCOUNT ON;SELECT COUNT(*) from sysobjects WHERE [name] = '%currentobject%') >%currentobject%_exists.sql
OSQL -Usa -P%password% -S %server% -d %db% -f 65001 -i %currentobject%_exists.sql


sqlcmd supports variables via the –v switch

pass.sql

SET NOCOUNT ON;
EXIT(SELECT 'filename passed is $(file)')

pass.bat

@echo off
for %%f in (*.bat) do (
sqlcmd -v file="%%f" -i "pass.sql"
)
)

Results -

B:\test2>pass


----------------------------
filename passed is check.bat


--------------------------------
filename passed is check_old.bat


---------------------------
filename passed is pass.bat


------------------------------
filename passed is rollout.bat



MSDN : osql
MSDN : sqlcmd
Using the SQLCMD command line utility for SQL SERVER
Mohamad Shehadeh's Blog : SQLCMD VS OSQL

Tuesday, 12 April 2011

(the deprecated) TEXT datatype

Argh! Have come up against the deprecated text datatype in a database i’m reporting on.
It’s a migrated SQL 2000 product in 8.0 Compatibility mode!

I cannot use equals (=) in a WHERE clause against the text column

So when I want to write
SELECT * FROM ProductUpdates WHERE Build = ‘9.71’
I get ...

Msg 402, Level 16, State 1, Line 1
The data types text and varchar are incompatible in the equal to operator.

I have to use PATINDEX to get around it, like this –
SELECT * FROM ProductUpdates  WHERE PATINDEX('9.71',Build) > 0
Or CAST the column like this
SELECT * FROM ProductUpdates  WHERE CAST(Build AS VARCHAR(MAX)) = ‘9.71’

Although this second approach would ruin the sargability of the query, i.e. the ability to use an index seek on the column.

Link : Using equal operator in transact-SQL for ntext datatype column

Monday, 11 April 2011

Codeplex : ExportSqlScript

I'm currently looking a replacing a product scripting system. It is command line driven (not a bad thing), but suffers from being overly complex. To apply changes, they need to be scripted to 3 places which is far from ideal. I need to create database build scripts that will support multiple versions, service packs and patches for a core product.

Redgate's SQL Compare is the obvious answer to see the initial state of play, but I cannot roll that out to the deployment team and tell them to get on with it. As much as I'd like to.

For this reason, some googling had led me to the perfect starting block, a codeplex project called 'ExportSqlScript'.

http://exportsqlscript.codeplex.com/

It is command line driven, and runs like this

ExportSQLScript.exe localhost adventureworks /ot:Tree /of:CreationOrder.txt /od:"b:\test2\ExportSqlScript" /ssq

This creates a folder for each object type (screenshot below) as well as CreationOrder.txt




CreationOrder.txt can be used to recreate the database as it takes into account object dependencies i.e. it creates views and constraints AFTER dependent tables and a functions / stored procedure after related tables / views. In theory it should match Jamie Thomon's Dependency Order script, that I always keep handy.

You can run scripts in order like this -
for /F "" %i in (CreationOrder.txt) do osql -Uuser -Ppassword -S localhost -d databasename -f 65001 -i %i

(Change %i for %%i inside a batch file)




Monday, 21 March 2011

Running Windows 2000 on Hyper-V

I recently tried to install a Windows 2000 VM for old times sake (well, for testing actually...).

If you attempt this, here's what to adhere to -
  1. Only configure 1 virtual processor
  2. Install SP4 (I had to use DoIso to get a downloaded SP4 inside to the VM)
  3. Install HyperV Integration services to the client VM 
  4. Enable networking in the VM (assign ip, subnet, gateway & dns)
  5. Run Windows Update (to get everything post SP4).
I had all kinds of fun before I settled on this order. An unpatched Windows 2000 installation comes with Internet Explorer 5. IE5 prevents connection to Windows Update and it's javascript handling prevents the download page for Service Pack 4 from functioning!

Mounting the host drive also proved problematic before SP4 was applied, with the Windows 2000 guest causing the host server to die with a BSOD.

Friday, 18 March 2011

Audit Scripts : When were SQL Server & Windows Installed?

What version of SQL Server are we running ?

SELECT @@version

Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009 10:11:52 Copyright (c) 1988-2008 Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.0 (Build 6002: Service Pack 2) 
 
When was SQL Server installed ?

SELECT  createdate as InstallDate 
FROM    sys.syslogins 
where   sid = 0x010100000000000512000000 

When was Windows installed ?

Open a command prompt, and type -

systeminfo | find /i "install date"

Links :
How to check when SQL Server was installed
How to check when Windows was installed

Wednesday, 16 March 2011

TSQL : Returning the SQL Server IP Address

I recently wrote some audit scripts and wanted to find the IP Address of the server from TSQL. The majority of the replies on twitter correlated with my google findings, i.e. to use extended stored procedure xp_cmdshell to run an operating system command.

Leaving security concerns aside , here's a reminder on enabling xp_cmdshell

Using xp_cmdshell to retrieve server ip address -

create table #cmdresults(ip varchar(255))
insert into #cmdresults exec xp_cmdshell'ipconfig | find "IP Address"'
select ltrim(rtrim(substring(ip,charindex(':',ip)+1,len(ip)))) from #cmdresults where ip is not null
drop table #cmdresults

On moving it to my server, I found it did not work. The difference being that I needed to look for 'IPv4 Address', not 'IP Address' on my Windows 2008 installs where entries for IPv4 and IPv6 could both exist.

A simpler version was suggested by Kendra Little (@Kendra_Little | blog) was to look at the connections dmv, like this

Using DMV to return session ip address -

SELECT local_net_address FROM sys.dm_exec_connections WHERE session_id=@@SPID 

This returns the connected client IP, so it only returns the server IP if you are working on your server (or an rdp session on it).

For the purpose of what I needed (reports emailed from the sql server), it is perfectly adequate (and tidier than xp_cmdshell).