Monday, 29 May 2006

Stored Procedures - Output Parameters

Demonstrates the use of the OUTPUT parameter from a stored procedure -
CREATE PROCEDURE dbo.GetCountByLastName (
@DepartmentName NVARCHAR(50),
@DepartmentCount INT OUTPUT )
AS
select @DepartmentCount = COUNT(*) from HumanResources.EmployeeDepartmentHistory h
inner join HumanResources.Department d
on h.DepartmentID = d.DepartmentID
where d.Name = @DepartmentName and EndDate IS NULL
group by d.Name


Call the procedure like this to fetch the output -
declare @intDepartmentCount int

exec dbo.GetCountByLastName
@DepartmentName = 'Marketing',
@DepartmentCount = @intDepartmentCount OUTPUT

select @intDepartmentCount  as DepartmentCount

Sunday, 28 May 2006

Occasional SQL User?


SQL Server runs as a service. Brilliant on a server, not so brilliant if you just wasn't to do the occasional bit of development on a laptop!

This is where placing a couple of batch files (remember them?) on your desktop can help.
Create two files, say StartSQL.bat and StopSQL.bat and place the following lines in them respectively.

net start mssqlserver

net stop mssqlserver

Then go to Services (located in Control Panel > Administrative Tools) and set SQL Server (MSSQLSERVER) to Manual startup.



Now, SQL wont start on reboot and you turn it on only when you need to.

Wednesday, 24 May 2006

Generic Cursor Template

Generic CURSOR Template -
DECLARE @Variable VARCHAR(200)
DECLARE CURSORNAME CURSOR FOR
SELECT ColumnName FROM Table         
OPEN CURSORNAME
FETCH NEXT FROM CURSORNAME INTO @Variable

WHILE @@FETCH_STATUS = 0
BEGIN

-- DO STUFF HERE !!

FETCH NEXT FROM CURSORNAME INTO @Variable
END

CLOSE CURSORNAME
DEALLOCATE CURSORNAME

Tuesday, 23 May 2006

SQL 2000 : Sending Mail WITHOUT Sql Mail

Creating the procedure -

create procedure [dbo].[CdoSysEMail] 
 (
 @email_from    varchar(200), 
 @email_to      varchar(200), 
 @email_bcc     varchar(200) = '', 
 @email_subject varchar(200) = '', 
 @email_body    varchar(7000) =''
 )
as 

begin
 -- declare variables
 declare @obj_message_id int 
 declare @output int 
 declare @error_output varchar(5000) 
 declare @error_source varchar(255) 
 declare @error_description varchar(1000) 
  
 -- create CDO.Message object 
 exec @output = sp_OACreate 'CDO.Message', @obj_message_id OUT 

 -- set server properties in the object
 exec @output = sp_OASetProperty @obj_message_id, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value','2' 
 exec @output = sp_OASetProperty @obj_message_id, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport").Value','25'
 exec @output = sp_OASetProperty @obj_message_id, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate").Value','0'
 exec @output = sp_OASetProperty @obj_message_id, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value', '193.19.88.36'

 -- save those properties
 exec @output = sp_OAMethod @obj_message_id, 'Configuration.Fields.Update', Null
 
 -- pass the procedure parameters through to the e-mail
 exec @output = sp_OASetProperty @obj_message_id, 'To', @email_to
 exec @output = sp_OASetProperty @obj_message_id, 'Bcc', @email_bcc
 exec @output = sp_OASetProperty @obj_message_id, 'From', @email_from
 exec @output = sp_OASetProperty @obj_message_id, 'Subject', @email_subject
 exec @output = sp_OASetProperty @obj_message_id, 'TextBody', @email_body

 -- send the email
 exec @output = sp_OAMethod @obj_message_id, 'Send', NULL
 
 -- error handling 
 if @output <> 0 
 begin
  declare @No Int
  Set @No=@output
  Select @No
      exec @output = sp_OAGetErrorInfo NULL, @error_source OUT, @error_description OUT
  if @output = 0
   begin
   Set @error_output = 'Error : ' + cast(@No As varchar) + ', Source: ' + @error_source + ', Description: ' + @error_description
   Raiserror(@error_output,16,1)
   end
  else
   begin
      Raiserror('could not determine error (sp_OAGetErrorInfo failed)', 16,1)
      end
 end
 
 -- clean up
 exec @output = sp_OADestroy @obj_message_id
end
go


Testing the procedure -

execute CdoSysEMail 
 @email_from ='sqladmin@mydomain.net',
 @email_to = 'recipient@mydomain.net', 
 @email_subject = 'test, please ignore!', 
 @email_body = 'test message body'

Friday, 19 May 2006

TSQL : Swap Databases

Swap databases code.

Useful for quickly switching content, e.g for websites.
ALTER DATABASE Database1  SET SINGLE_USER with rollback immediate
ALTER DATABASE Database2  SET SINGLE_USER with rollback immediate

EXEC sp_renamedb 'Database1', 'Database3'
EXEC sp_renamedb 'Database2', 'Database1'
EXEC sp_renamedb 'Database3', 'Database2'

ALTER DATABASE Database1  SET MULTI_USER
ALTER DATABASE Database2  SET MULTI_USER

Monday, 15 May 2006

TSQL : Restoring a database to a point in time (Litespeed version)

Sql to restore LiteSpeed backups.

-- restore main bak first

exec master.dbo.xp_restore_database
@database = 'Accounts' ,
@filename = '\\FILESTORE\SQL$\Accounts\Accounts_20060502001507_Friday_LS.bak' ,
@filenumber = 1,
@with = 'NORECOVERY',
@with = 'NOUNLOAD',
@with = 'STATS = 10',
@with = 'REPLACE'
go

-- restore latest diff

exec master.dbo.xp_restore_database
@database = 'Accounts',
@filename = '\\FILESTORE\SQL$\Accounts\Accounts_20060502014913_Thursday.diff',
@filenumber = 1,
@with = 'NORECOVERY',
@with = 'NOUNLOAD',
@with = 'STATS = 10',
@with = 'REPLACE'
go

-- restore transaction log backups
-- repeat for each one, changing NORECOVERY to RECOVERY for the last one.

exec master.dbo.xp_restore_database
@database = 'Accounts',
@filename = '\\FILESTORE\SQL$\Accounts\Accounts_20060502060107_Thursday.trn',
@filenumber = 1,
@with = 'NORECOVERY',
@with = 'NOUNLOAD',
@with = 'STATS = 10',
@with = 'REPLACE'
go

Saturday, 13 May 2006

TSQL : Restoring a database to a point in time

Sql to use once you have identified which backup files need to be restored...
-- restore last full backup
-- use NORECOVERY to state you want to add further backup files

RESTORE DATABASE Sales
FROM DISK = '\\FILESTORE\SQL$\Sales\Sales_20060423180002_Wednesday_MS.bak'
WITH NORECOVERY

-- add last differential backup
-- use NORECOVERY to state you want to add further backup files

RESTORE DATABASE Sales
FROM DISK = '\\FILESTORE\SQL$\Sales\Sales_20060425010002_Friday.diff'
WITH NORECOVERY
go

-- apply transaction log backups , up until the point you wish to restore to
-- use NORECOVERY to state you want to add further backup files
-- on the final restore, omit WITH NORECOVERY or specify WITH RECOVERY so the db is readable.

RESTORE LOG Sales FROM DISK = '\\FILESTORE\SQL$\Sales\Sales_20060425060000_Friday_MS.trn' WITH NORECOVERY
RESTORE LOG Sales FROM DISK = '\\FILESTORE\SQL$\Sales\Sales_20060425070000_Friday_MS.trn' WITH NORECOVERY
RESTORE LOG Sales FROM DISK = '\\FILESTORE\SQL$\Sales\Sales_20060425080000_Friday_MS.trn' WITH NORECOVERY
RESTORE LOG Sales FROM DISK = '\\FILESTORE\SQL$\Sales\Sales_20060425090000_Friday_MS.trn' WITH NORECOVERY
RESTORE LOG Sales FROM DISK = '\\FILESTORE\SQL$\Sales\Sales_20060425100000_Friday_MS.trn' WITH NORECOVERY
RESTORE LOG Sales FROM DISK = '\\FILESTORE\SQL$\Sales\Sales_20060425110000_Friday_MS.trn' WITH NORECOVERY
RESTORE LOG Sales FROM DISK = '\\FILESTORE\SQL$\Sales\Sales_20060425120000_Friday_MS.trn'
go

Friday, 12 May 2006

SQL 2005 - Overview

SQL 2005 Management Studio
'Management Studio' is the primary interface for managing SQL 2005 servers and is backwards compatible with older servers.
It acts as the replacement for the main SQL 2000 tools, namely 'Enterprise Manager' , 'Query Analyser' and 'Analysis Manager'.
Management Studio Overview
SSIS - Sql Server Integration Services
In Sql Server 2005, The DTS (Data Transformation Services) functionality has been replaced with SSIS - Sql Server Integration Services.
SSIS is an installable component and provides powerful ETL (extraction, transformation & loading) capability.
SSIS supports automation in the same was that DTS packages could be executed and monitored from within other languages.
To design 'Integration Services' projects you use the Business Intelligence Studio Interface (also used for Analysis Services & Reporting Services components). If you already have Visual Studio 2005 installed, SQL 2005 projects fall within the 'Business Intelligence Projects' project type.
To execute 'Integration Services' projects you use 'SQL Server Management Studio'.
Integration Services Resources
Analysis Services 2005
Analysis Services was present on Sql Server 2000.
Like its predecessor, Analysis Services 2005 allows you to create and manage OLAP (Online Analytical Processing) cubes.
Unlike its predecessor, Analysis Services 2005 makes the task a lot easier by combining old Enterprise Manager, Query Analyser and DTS functionality.
'Analysis Services' projects are designed within the Business Intelligence Studio Interface (also used for Integration Services & Reporting Services components). If you already have Visual Studio 2005 installed, SQL 2005 projects fall within the 'Business Intelligence Projects' project type.
Analysis Services Resources
SSRS - Sql Server Reporting Services
Originally an add-on to SQL 2000, Sql Server Reporting Services is included in SQL 2005 for free.
It consists of 2 components, 'Report Designer' and 'Report Builder'
Report Designer features a 'drag and drop' interface and will be familiar to developers who have used Crystal Reports or Access.
Report Builder is an adhoc reporting tool which allows users to specify
A unique feature of SSRS (at this time) is that it allows users to subscribe to reports and features the functionality to have these reports emailed out periodically. Licencing for SSRS is free, which should accelerate its take up in the market place.
Reporting Services Resources

Thursday, 11 May 2006

ASCII Values Chart

System Characters
decimalcodemeaning
0NULNULL
1SOHStart Of Heading
2STXStart Of Text
3ETXEnd Of Text
4EOTEnd Of Transmission
5ENQEnquiry,
6ACKAcknowledge
7BELBell
8BSBackspace
9HTHorizontal Tabulation
10LFLine Feed
11VTVertical Tabulation
12FFForm Feed
13CRCarriage Return
14SOShift Out
15SIShift In
16DLEData Link Escape
17DC1Device Control 1,
18DC2Device Control 2
19DC3Device Control 3,
20DC4Device Control 4
21NAKNegative Acknowledge
22SYNSychronous Idle
23ETBEnd of Transmission Block
24CANCancel
25EMEnd of Medium
26SUBSubstitute
27ESCEscape
28FSFile Separator
29GSGroup Separator
30RSRecord Separator
31USUnit Separator
 
Printable Characters
 
decimalcharacterhexoct
32(space)2040
33!2141
34"2242
34"2242
35#2343
36$2444
37%2545
38&2646
38&2646
39'2747
40(2850
41)2951
42*2A52
43+2B53
44,2C54
45-2D55
46.2E56
47/2F57
4803060
4913161
5023262
5133363
5243464
5353565
5463666
5573767
5683870
5793971
58:3A72
59;3B73
60<3C74
60<3C74
61=3D75
62>3E76
62>3E76
63?3F77
63?3F77
63?3F77
64@40100
65A41101
66B42102
67C43103
68D44104
69E45105
70F46106
71G47107
72H48110
73I49111
74J4A112
75K4B113
76L4C114
77M4D115
78N4E116
79O4F117
80P50120
81Q51121
82R52122
83S53123
84T54124
85U55125
86V56126
87W57127
88X58130
89Y59131
90Z5A132
91[5B133
92\5C134
93]5D135
94^5E136
95_5F137
96`60140
97a61141
98b62142
99c63143
100d64144
101e65145
102f66146
103g67147
104h68150
105i69151
106j6A152
107k6B153
108l6C154
109m6D155
110n6E156
111o6F157
112p70160
113q71161
114r72162
115s73163
116t74164
117u75165
118v76166
119w77167
120x78170
121y79171
122z7A172
123{7B173
124|7C174
125}7D175
126~7E176
12880200
 
Extended Characters
 
12981201
13082202
131ƒ83203
13284204
13385205
13486206
13587207
136ˆ88210
13789211
138Š8A212
1398B213
140Œ8C214
1418D215
142Ž8E216
1438F217
14490220
14591221
14692222
14793223
14894224
14995225
15096226
15197227
152˜98230
15399231
154š9A232
1559B233
156œ9C234
1579D235
158ž9E236
159Ÿ9F237
161¡A1241
162¢A2242
163£A3243
164¤A4244
165¥A5245
166¦A6246
167§A7247
168¨A8250
169©A9251
169©A9251
170ªAA252
171«AB253
172¬AC254
173­AD255
174®AE256
174®AE256
175¯AF257
176°B0260
177±B1261
178²B2262
179³B3263
180´B4264
181µB5265
182B6266
183·B7267
184¸B8270
185¹B9271
186ºBA272
187»BB273
188¼BC274
189½BD275
190¾BE276
191¿BF277
192ÀC0300
192ÀC0300
193ÁC1301
193ÁC1301
194ÂC2302
194ÂC2302
195ÃC3303
195ÃC3303
196ÄC4304
196ÄC4304
197ÅC5305
197ÅC5305
198ÆC6306
198ÆC6306
199ÇC7307
199ÇC7307
200ÈC8310
200ÈC8310
201ÉC9311
201ÉC9311
202ÊCA312
203ËCB313
203ËCB313
204ÌCC314
204ÌCC314
205ÍCD315
205ÍCD315
206ÎCE316
206ÎCE316
207ÏCF317
207ÏCF317
208ÐD0320
208ÐD0320
209ÑD1321
209ÑD1321
210ÒD2322
211ÓD3323
212ÔD4324
213ÕD5325
213ÕD5325
214ÖD6326
214ÖD6326
215×D7327
216ØD8330
216ØD8330
217ÙD9331
217ÙD9331
218ÚDA332
218ÚDA332
219ÛDB333
219ÛDB333
220ÜDC334
220ÜDC334
221ÝDD335
221ÝDD335
222ÞDE336
222ÞDE336
223ßDF337
223ßDF337
224àE0340
224àE0340
225áE1341
225áE1341
226âE2342
227ãE3343
228äE4344
229åE5345
229åE5345
230æE6346
230æE6346
231çE7347
231çE7347
232èE8350
232èE8350
233éE9351
233éE9351
234êEA352
234êEA352
235ëEB353
235ëEB353
236ìEC354
236ìEC354
237íED355
237íED355
238îEE356
238îEE356
239ïEF357
239ïEF357
240ðF0360
240ðF0360
241ñF1361
241ñF1361
242òF2362
242òF2362
243óF3363
243óF3363
244ôF4364
244ôF4364
245õF5365
245õF5365
246öF6366
246öF6366
247÷F7367
248øF8370
248øF8370
249ùF9371
249ùF9371
250úFA372
250úFA372
251ûFB373
251ûFB373
252üFC374
253ýFD375
253ýFD375
254þFE376
254þFE376
255ÿFF377

Backup Stored Procedures

Script from a colleague.
This could be scheduled to backup code.
Particularly useful in development environments -


CREATE PROCEDURE dbo.StoredProcBackup_sp

@DatabaseName as varchar(200) = 'DATABASENAME IN HERE',
@DestinationDir as varchar(200) = 'D:\SQLDATA\MSSQL\BACKUP\StoredProcedures\AND THE REST OF YOUR PATH',
@User as varchar(20)= 'USER',
@Password as varchar(20) = 'PASSWORD'
AS

set nocount on

declare @dircreatecmd as varchar(210)
declare @Error int
declare @RootDir varchar(210)
declare @RootDay varchar(215)
declare @CheckDircmd varchar(300)

set @CheckDircmd = 'dir ' + @DestinationDir
EXEC @Error =  master..XP_CMDSHELL @CheckDircmd
If @Error = 1
 Begin
 --Directory does not exist so create it
 set @RootDir =  @DestinationDir
 set @dircreatecmd = 'mkdir ' + @RootDir
 EXEC master..XP_CMDSHELL @dircreatecmd
 End 
Declare @Day varchar(2)
Declare @Month varchar(2)
set @Day = convert(varchar(2),DATEPART(dd,getDate()))
set @Month = convert(varchar(2),DATEPART(mm,getDate()))

set @RootDay = @DestinationDir +'\'+ @Month + '\' + @Day + '\' 
declare @CheckRootDaycmd varchar(320)

set @CheckRootDaycmd = 'Dir ' + @RootDay
EXEC @Error =  master..XP_CMDSHELL @CheckRootDaycmd
If @Error = 1
 Begin
 --Directory does not exist so create it
 set @RootDir =  @RootDay
 set @dircreatecmd = 'mkdir ' + @RootDir
 EXEC master..XP_CMDSHELL @dircreatecmd
 End 

Declare @ProcName varchar(100)
Declare @ProcText varchar(8000)
Declare @filename varchar(104)
Declare @FilePath varchar(310)
DECLARE @cmd varchar (8000), @var varchar (8000)

-- backup all stored procs into single file.
EXEC master..xp_cmdshell 'osql -U?? -P?????? -Q"SELECT rtrim(ltrim(text))  FROM DATABASENAME.dbo.sysobjects so join DATABASENAME.dbo.syscomments sc on so.id = sc.id where type = ''p''" -dDATABASE -oD:\SQLDATA\MSSQL\BACKUP\StoredProcedures\REST OF YOUR PATH\AllStoredProcs_CURRENT.txt'


Declare BackupTables_cur cursor for

-- select all the stored procedures from the given database

SELECT name, text FROM DATABASENAME.dbo.sysobjects  so,  DATABASENAME.dbo.syscomments sc
where so.id = sc.id
and type = 'p'

Open BackupTables_cur

Fetch Next from BackupTables_cur into @ProcName, @ProcText
While @@Fetch_Status = 0
Begin
 Print @ProcName
 Print  @ProcText
 Print @Day
 Set @filename = @ProcName + '.txt'
 set @FilePath = @DestinationDir +'\'+ @Month + '\' + @Day + '\' + @filename

  
 DECLARE @FS int, @OLEResult int, @FileID int
 
 
 EXECUTE @OLEResult = sp_OACreate 'Scripting.FileSystemObject', @FS OUT
 IF @OLEResult <> 0 PRINT 'Scripting.FileSystemObject'
 
 --Open a file
 execute @OLEResult = sp_OAMethod @FS, 'OpenTextFile', @FileID OUT, @FilePath, 8, 1
 IF @OLEResult <> 0 PRINT 'OpenTextFile'
 
 --Write Text1
 execute @OLEResult = sp_OAMethod @FileID, 'WriteLine', Null, @ProcText
 IF @OLEResult <> 0 PRINT 'WriteLine'
 
 EXECUTE @OLEResult = sp_OADestroy @FileID
 EXECUTE @OLEResult = sp_OADestroy @FS

 Fetch Next from BackupTables_cur into @ProcName, @ProcText
End
Close BackupTables_cur
Deallocate BackupTables_cur

set nocount off
GO

Wednesday, 10 May 2006

UltraEdit Macro - Delete all blank lines

Ultraedit

Top
TrimTrailingSpaces
Loop
Find "^p^p"
Replace All "^p"
IfNotFound
ExitLoop
EndIf
EndLoop

Tuesday, 9 May 2006

UltraEdit Macro - Delete after comma

Macro for UltraEdit
Deletes everything after the final comma ',' on all lines
InsertMode
ColumnModeOff
Key HOME
HexOff
UnixReOff
Loop 
IfEof
ExitMacro
Else
Key END
Find Up ","
StartSelect
Key END
Key BACKSPACE
EndSelect
Key DOWN ARROW
EndLoop

Sunday, 7 May 2006

Backup Batch File

Schedule weekly to hold 5 weeks of history of important folders >

rd /s/q u:\backup\5

ren u:\backup\4 5
ren u:\backup\3 4
ren u:\backup\2 3
ren u:\backup\1 2
md u:\backup\1
xcopy c:\my documents\*.* u:\backup\1\*.* /r/v/y/s 

Thursday, 4 May 2006

Exchange 2003 : Exmerge Permissions Problem

Solution that worked for me (14/03/03) >

You should have to give your account permission to enter all messages in all data stores.

The access to user mailboxes is controlled by two permissions Send As / Receive As , you can grant your account those rights in the Exchange manager then you will be able to access all mailboxes.

To do it open the Exchange system manager locate you server on the permission tab remove the inherited permission select copy and remove the deny Send As / Receive As from the groups you are member of.
These are domain admins and enterprise admins grant your account those two permissions.

Or give the permission at the organization level >

Add the following registry key

HKEY_CURRENT_USER\Software\Microsoft\Exchange\EXAdmin New dword 'ShowSecurityPage' value=00000001
After you add this key you will find the permission page on all objects.
In the level you want (you can do it for all the organization)
Remove the deny from the send as and receive as permissions from the groups you are member of the default is deny to the domain admins and enterprise admins )
Grant yourself those two permissions.

Exchange 2003 : Compressing Mailbox Store

Overview :

Over time, the mailbox store grows and also becomes fragmented with the constant addition and deletion of mailboxes and messages. After clearing out old user mailboxes and deleting large volumes of messages, the data store file needs some housekeeping i.e. compacting and reordering.

Notes :

Perform the following steps when no users are using the mail server (preferably out of hours).

Solution :

1 Ensure you have up to date backups of mail data.

2 Disable the NIC (network interface card) by right clicking it's icon in the task bar (labelled Local Area Connection') and selecting 'disable'.

3 Stop all the Exchange services. These are easily identified as they all start with 'Microsoft Exchange'. To control services, go to 'Control Panel' , 'Administrative Tools' and then 'Services'.

4 Start a DOS session by selecting Start > Run , then typing 'cmd' .

5 Change to drive c: by typing 'c:'

6 Change the working directory to the exchange application directory by typing 'cd program files\exchsrvr\bin' .

7 Assuming the location of the message store files has not changed, type the following to compact the mailstore.
eseutil /d /o 'c:\program files\exchsrvr\mdbdata\priv1.edb'

This task may take a while depending on the volume of work it has to do.
The following test is taken from a screenshot when the task completes.

C:\Program Files\Exchsrvr\BIN>eseutil /d /o 'c:\program files\exchsrvr\mdbdata\priv1.edb'
Initiating DEFRAGMENTATION mode...
Database: c:\program files\exchsrvr\mdbdata\priv1.edb
Streaming File: c:\program files\exchsrvr\mdbdata\priv1.STM
Temp. Database: TEMPDFRG5160.EDB
Temp. Streaming File: TEMPDFRG5160.STM
Defragmentation Status (% complete) 0 10 20 30 40 50 60 70 80 90 100
|----|----|----|----|----|----|----|----|----|----| ...................................................
Moving 'TEMPDFRG5160.EDB' to 'c:\program files\exchsrvr\mdbdata\priv1.edb'... DONE!
Moving 'TEMPDFRG5160.STM' to 'c:\program files\exchsrvr\mdbdata\priv1.stm'... DONE!

Note:
It is recommended that you immediately perform a full backup of this database.
If you restore a backup made before the defragmentation, the database will be rolled back to the state it was in at the time of that backup.
Operation completed successfully in 369.938 seconds.

C:\Program Files\Exchsrvr\BIN>

To complete the task, restart the server. This will re-establish all the exchange services on startup.
The server should be rebooted periodically anyway hence this is an ideal opportunity.

Tuesday, 2 May 2006

SQL 101 : Network Debugging

Testing Connectivityping / tracert / pathping
Establish session on Port number telnet
Server Name Lookup NSLookup
View / Configure IP Address ipconfig