Sunday 25 March 2007

Virtual PC Keystrokes

Virtual PC is running full screen and the menu bar has gone.
You want to log on to your VM.

Q) How do you perform CTRL-ALT-DEL n Virtual PC, without sending those keys to the host?
A) ALT-GR-DEL (aka Right ALT-DEL)


SC (Service Controller)

Common Uses - List all running services >

C:\>sc query
These tend to fly past pretty fast, hence pipe the results into a text file for later eg >

C:\>sc query >services.txt
To return data for just one service >

C:\>sc query "mssql$alpha" SERVICE_NAME: mssql$alpha TYPE : 10 WIN32_OWN_PROCESS STATE : 4 RUNNING (STOPPABLE,PAUSABLE,ACCEPTS_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x0

To delete a service (stop the service first) >

C:\>sc delete "Unwanted Service Name" [SC] DeleteService SUCCESS

Find it on Technet here >
http://technet2.microsoft.com/windowsserver2008/en/library/ac365f89-4b20-4de6-a582-b204c5e7d0eb1033.mspx?mfr=true

Saturday 24 March 2007

Remote Shutdown / Restart

Ran into a server that wouldnt restart today.
Sent a ping -t servername and it just kept responding, showing it had no intention of shutting down, let alone starting up again.

A colleague showed me how to remotely force the restart via the shutdown command.
I've seen these utilities on older OSs before, but have never had the cause to use them myself as i'd always phoned a sysadmin to do so!

The shutdown utility >

C:\>shutdown
Usage: shutdown [-i | -l | -s | -r | -a] [-f] [-m \\computername] [-t xx] [-c "comment"] [-d up:xx:yy]

No args Display this message (same as -?)
-i Display GUI interface, must be the first option
-l Log off (cannot be used with -m option)
-s Shutdown the computer
-r Shutdown and restart the computer
-a Abort a system shutdown
-m \\computername - Remote computer to shutdown/restart/abort
-t xx Set timeout for shutdown to xx seconds
-c "comment" Shutdown comment (maximum of 127 characters)
-f Forces running applications to close without warning
-d [u][p]:xx:yy The reason code for the shutdown
u is the user code
p is a planned shutdown code
xx is the major reason code (positive integer less than 256)
yy is the minor reason code (positive integer less than 65536)

We needed the -f option to force the restart, -r (restart NOT shutdown - kind of crucial to prevent embarassment) and -m as it was a remote box (if it was next to me i would have unplugged it right? ;) )

shutdown -r -m \\servername -f
shutdown -i gives you an interface which you may find more friendly than the command line >

Tuesday 20 March 2007

Disable all Constraints, Foreign Keys and Triggers

Disable all Constraints, Foreign Keys and Triggers for current database, Sql 2005+

To TRUNCATE tables however, you will need to drop and recreate the keys.
-- loop through tables, turning off check constraints and triggers for each
sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? NOCHECK CONSTRAINT all"
go
sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? DISABLE TRIGGER  all"
go

-- do data load or deletes here

-- loop through tables, turning back on check constraints and triggers for each
sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? CHECK CONSTRAINT all"
go
sp_msforeachtable @command1="print '?'", @command2="ALTER TABLE ? ENABLE TRIGGER  all"
go

Saturday 17 March 2007

Activity Monitor : #tmpDBCCinputbuffer

In Activity Monitor you see a mystery command, apparently executed by yourself, with 2 open transactions and coming from application 'Microsoft SQL Server Management Studio'.

Double clicking the row, gives you the Last Transact-SQL command batch >
" create table #tmpDBCCinputbuffer ([Event Type] nvarchar(512), [Parameters] int, [Event Info] nvarchar(512))
insert into #tmpDBCCinputbuffer exec ('DBCC INPUTBUFFER(319)')
select [Event Info] from #tmpDBCCinputbuffer "

Simple Answer is DONT PANIC!

It is simply the tsql generated by viewing process info in Activity Monitor itself.
The DBCC command you see is it fetching the information from the last time you double clicked an Activity Monitor row to see the last TSQL.

Of course, the irony of this is that by looking at the row, you've now changed the data.
You're looking at a system process row generated by looking at the system processes...

Wednesday 7 March 2007

SQL 2000 to 2005 Migration Script for databases

This needs to be run from SQL 2005 instance with a linked server named link2000
linking to the 2000 instance. The 'RPC Out' option for the linked server needs to be set
to TRUE to allow stored procedures to be executed remotely.

For the 2005 instance, the script requires -
( 1 ) USP_KillAllConnections to be present in master database
( 2 ) USP_FixUsers to be present in the master database
( 3 ) Full control over the path specified in @backupdirectory parameter

Usage :
( 1 ) Change the value of @chvDataBaseName on line 10 to the database to be migrated and the directory locations in lines 11, 12 & 13
( 2 ) Execute script from the 2005 instance the restores are occuring to.


declare @chvDataBaseName varchar(100)
declare @sql nvarchar(2000)
declare @output nvarchar(2000)
declare @backupdirectory nvarchar(200)
declare @newdatadirectory nvarchar(200)
declare @newlogdirectory nvarchar(200)
declare @logicaldataname nvarchar(200)
declare @logicallogname nvarchar(200)

set @chvDataBaseName = 'TestDataBaseToRestore'
set @backupdirectory = '\\server\share$\TEMP2005MIGRATIONSTORE\'
set @newdatadirectory = 'H:\Penfold\'
set @newlogdirectory = 'H:\Penfold\'

-- backup on remote server
print '------------'
print 'start backup'
print '------------'
 set @sql =       N' BACKUP DATABASE ' + @chvDataBaseName  
 set @sql = @sql + ' TO DISK = N''' + @backupdirectory
 set @sql = @sql + @chvDataBaseName + '.BAK'' WITH NOFORMAT, INIT,'
 set @sql = @sql + ' NAME = N''Full Database Backup'',' 
 set @sql = @sql + ' SKIP, NOREWIND, NOUNLOAD, STATS = 10'
 print @sql
execute link2000.master.dbo.sp_executesql @sql
print '----------'
print 'end backup'
print '----------'

-- kill connections on remote (if db exists)
print '----------------'
print 'kill connections'
print '----------------'
 set @sql = N'dbo.master.USP_KillAllConnections ' + @chvDataBaseName + ''
execute master.dbo.sp_executesql @sql


-- restore on local server
print '-------------'
print 'start restore'
print '-------------'

-- fetch filenames for restore

-- use temp table to hold output of restore file list
if object_id('tempdb..#filelist') is not null 
 begin
 drop table #filelist
 end

create table #filelist
(LogicalName nvarchar(128) 
,PhysicalName nvarchar(260) 
,Type char(1) 
,FileGroupName nvarchar(128) 
,Size numeric(20,0) 
,MaxSize numeric(20,0)
,Fileid tinyint
,CreateLSN numeric(25,0)
,DropLSN numeric(25, 0)
,UniqueID uniqueidentifier
,ReadOnlyLSN numeric(25,0)
,ReadWriteLSN numeric(25,0)
,BackupSizeInBytes bigint
,SourceBlocSize int
,FileGroupId int
,LogGroupGUID uniqueidentifier
,DifferentialBaseLSN numeric(25,0)
,DifferentialBaseGUID uniqueidentifier
,IsReadOnly bit
,IsPresent bit 
)

set @sql = 'RESTORE FILELISTONLY FROM DISK = N'''+ @backupdirectory + @chvDataBaseName + '.BAK'''
insert into #filelist
exec (@sql)

select @logicaldataname = logicalname
  from #filelist
 where Type = 'D'

select @logicallogname = logicalname
  from #filelist
 where Type = 'L'

set @sql =        ' RESTORE DATABASE ' + @chvDataBaseName  
set @sql = @sql + ' FROM DISK = N'''+ @backupdirectory + @chvDataBaseName + '.BAK'''
set @sql = @sql + ' WITH REPLACE ,'
set @sql = @sql + ' MOVE ''' + @logicaldataname + ''' TO ''' + @newdatadirectory + @chvDataBaseName + '.mdf' + ''','
set @sql = @sql + ' MOVE ''' + @logicallogname + ''' TO ''' + @newlogdirectory + @chvDataBaseName + '.ldf' + ''''
print @sql
EXEC(@sql)
print '-----------'
print 'end restore'
print '-----------'

print '------------------'
print 'change owner to sa'
print '------------------'
set @sql = 'exec '+ @chvDataBaseName + '.dbo.sp_changedbowner ''sa'' '
print @sql
execute master.dbo.sp_executesql @sql

print '--------------'
print 'add datareader'
print '--------------'
set @sql = 'exec '+ @chvDataBaseName + '.dbo.sp_addrolemember ''db_datareader'',''applicationuser'' '
print @sql
execute master.dbo.sp_executesql @sql

print '--------------'
print 'add datawriter'
print '--------------'
set @sql = 'exec '+ @chvDataBaseName + '.dbo.sp_addrolemember ''db_datawriter'',''applicationuser'' '
print @sql
execute master.dbo.sp_executesql @sql

print '--------------'
print 'reattach users'
print '--------------'
set @sql = 'exec '+ @chvDataBaseName + '.dbo.USP_FixUsers'
print @sql
execute master.dbo.sp_executesql @sql

print '-------------------'
print 'alter schema to dbo'
print '-------------------'
set @sql = 'exec '+ @chvDataBaseName + '.dbo.sp_MSforeachtable "PRINT ''? modify''; ALTER SCHEMA dbo TRANSFER ?; IF @@ERROR = 0 PRINT ''? modified''; PRINT ''''" '
print @sql
execute master.dbo.sp_executesql @sql

print '--------------------------------------'
print 'report unmapped users - should be none'
print '--------------------------------------'
set @sql = 'exec '+ @chvDataBaseName + '.dbo.sp_change_users_login ''report'''
print @sql
execute master.dbo.sp_executesql @sql

Saturday 3 March 2007

Determine ASCII values of characters in a string

Determine ASCII values of characters in a string
-- script to determine ascii values of characters in data
-- adjust it to point at a table, not the test string!

set rowcount 1
declare @Cnt int
declare @charcount int
declare @title varchar(500)

select @Cnt = 1

declare @Characters table
(
rownum int IDENTITY (1, 1) Primary key NOT NULL ,
letter char(1),
val int
)


select @title = 'the quick brown fox, jumped over the lazy dog'
-- select @title = column from table where criteriacolumn = criteriavalue

select @charcount = len(@title)
print @title

while @Cnt <= @charcount
begin
insert into @Characters (letter,val)
select substring(@title,@cnt,1), ascii(substring(@title,@cnt,1))
print substring(@title,@cnt,1)
print ascii(substring(@title,@cnt,1))
Select @Cnt = @Cnt + 1
end
set rowcount 0