View
120
Download
1
Category
Preview:
DESCRIPTION
One of our Microsoft SQL Server consultants gives us a handy tip for writing a SQL script for many different versions of SQL Server.
Citation preview
• Supporting different versions
of SQL is a daily challenge for
a DBA
• One of our Microsoft SQL
Server consultants discovered
a handy tip
• One script for many different
versions of SQL server
SQL SERVER
I start writing this on my new SQL
Server 2012 box and quickly decide
to use the Dynamic Management
Views (DMV’s)
-- using DMV os Performance stats
SELECT instance_name
,cntr_value 'Log File(s) Used Size (KB)'
FROM sys.dm_os_performance_counters
WHERE counter_name = 'Log File(s) Used Size
(KB)'
I START WITH SOMETHING LIKE…
• This runs well on my SQL Server
2012, 2008r2 and SQL 2005 servers
• SQL Server 2000 server simply
comes back with “object not found”
• In 2000 days, I have to use the DBCC
command SQLPERF to get the log
size
OF COURSE, SQL SERVER 2000
DIDN’T HAVE DMV’S…
cre
ate
table
#dbccre
sults
( DB
Nam
e[v
arc
har]
(255
),
LogS
ize_M
Bdecim
al(18,
8),
LogS
paceU
sed
decim
al(18,
8),
sta
tus int)
--G
et th
e L
og f
ile s
izes
insert
into
#dbccre
sults
exec (
'dbcc
sqlp
erf
(logspace)')
--O
utp
ut th
e r
esults
sele
ct *
from
#dbccre
sults
--U
SIN
G D
BC
C S
QL
PE
RF
(LO
GS
PA
CE
);
CR
EA
TE
A T
AB
LE
• Write our scripts to ensure they check
the version of SQL Server first
• run the relevant piece of SQL based
on the version of SQL that part of the
script supports
• To do this we use
SERVERPROPERTY this is
supported in all version of SQL and
likely to be ever more.
1 SCRIPT THAT DOES BOTH
This will output the following based on the current version of SQL Server:
8 – SQL Server 2000
9 – SQL Server 2005
10 – SQL Server 2008
11 – SQL Server 2012
If we use this in our script with an IF
statement then we can allow our DMV
script to work on SQL Server 2005
onwards and our DBCC script to run on
SQL Server 2000 servers.
--R
un if S
QL S
erv
er
2000
IF S
ELE
CT
CA
ST
(LE
FT
(SE
RV
ER
PR
OP
ER
TY
('pro
ductv
ers
ion'), 2)
as int)
= 8
BE
GIN
--usin
g D
BC
C S
QLP
ER
F(L
OG
SP
AC
E);
--C
reate
a t
em
p t
able
cre
ate
table
#dbccre
sults
( DB
Nam
e[v
arc
har]
(255),
LogS
ize_M
Bdecim
al(18,
8),
LogS
paceU
sed
decim
al(18,
8),
sta
tus int)
--G
et th
e L
og f
ile s
izes
insert
into
#d
bccre
sults
exec (
'dbcc
sqlp
erf
(logspace)')
--O
utp
ut th
e r
esults
sele
ct *
from
#dbccre
sults
EN
D
-- Run if SQL Server 2005 or above
IF SELECT CAST(LEFT(SERVERPROPERTY ('productversion'), 2) as int) = 8
BEGIN
-- using DMV os Performance stats
SELECT instance_name
,cntr_value 'Log File(s) Used Size (KB)'
FROM sys.dm_os_performance_counters
WHERE counter_name = 'Log File(s) Used Size (KB)'
END
You can use this method to do any
number of checks, and it’s always
there in the kitbag for when
needed
1 SCRIPT TO RULE THEM ALL…
Recommended