Gerard's codebase

This is a personal repository of code snippets and information.

Over the years I have generated lots of little sub programs and stored away acres of useful code snippets. The problem is always to locate them.

Even more time wasting is forgetting how to do simple things when you havnt developed in an environment for a few years (or even a few months)

My new years resolution is to start putting them up in a common place as I produce them. (thanks google)

They are handy for me and, with a bit of a clean up and documentation, they might be handy for others if they wander in here.

Gerard 2008

Tuesday, June 21, 2011

SQL Server Db stuck in restore state

It is possible to end up with a database stuck in a restoring state either you have specified the restore with no recovery or the client has disconnected whilst the restore is running or you have run out of disk space.

If the situation is that the database has fully restored but has not not recieved the recover command the following tSQL will put it back to an operational state

RESTORE DATABASE WITH RECOVERY

Sunday, May 8, 2011

DLink DNS 323

The DNS 323 is a relatively cheap ~$150 Network Attached Storage device (NAS) that I use at home to store all the important stuff (family photos etc), back and synchronize my work directories on all my computers and to stream movies to our PS3 (unfortunately cannot stream microsoft's TV format - .wtv)

It has a little 200mhz ARM processor running a cut down version in Linux and a web interface to make all setup and changes.

Here is the link to its homepage
http://www.dlink.com/products/?pid=DNS-323
Basic services offered are:
  • NAS disk share
  • AV server for streaming media
  • USB port to attach a network printer (see notes on SharePort utility below- don't even bother trying to use it as a print server as DLink advertises)
  • ftp server
  • iTunes server
  • + a few others
  • + you can install other Linux packages if you are technical
Overall I am very happy with it for the last 4 years. It has gone through a series of drives and a series of RAID configurations as I have filled it up and run out of space. There are few things to both know and be aware of with it though - here is a list of what I am aware of

Disk Size - 2TB now supported
With firmware v1.8 or v1.9 installed it is capable of holding 2 X 2TB disks. Yay. Be careful of the disks you buy though. DLink has tested only Western Digital WD20EADS 2TB drives. There are potential problems with (most) 2TB disks on the market using the newer 4K sectors and AFT technology. Look into it very carefully before you buy a disk. I just went with the DLink recommended WD disks - be careful they are the exact ones though - the WD20EARS 2TB drives do not work (1 character different - beware)

Speed
The 323 is very slow in file transfers to windows machines. A fair bit of this is due to the SAMBA configuration on the 323, a fair bit due to the limited CPU and a fair but due to the windows configurations and network card used. Basically this device is not up to much with its little ARM processor and the SAMBA configuration as set up is very CPU intensive with 64K buffers. In addition file transfers will be slower if the windows machine has a low powered CPU. Still - it streams HD no problems for me.

Use FTP. If you are doing a lot of large file transfers turn on the built in ftp server and use ftp to transfer the files. You will find it will be double the speed. Filezilla is a good ftp client for windows.

SharePort Utility
This DLink utility shares the USB port on the back of the 323 across the network. I use it to share a Lexmark 3200 series printer. The concept is great - apparently if you attach a powered USB hub you can share multiple devices.

I couldn't get SharePort working but eventually struck on the magic combination. I had initially installed v1.17 addon and on the 323 and was using 1.17 windows utility software on my PC. It could not see any in USB device inserted into the 323

The magic combination (for me) was SharePort v1.17 addon on the 323 and SharePort v3.0 windows utility software on my PC.

I will update this post if I find anything else to be aware of about this great little box. Feel free to add comments if you know of any other "gotchya's"

Sunday, January 2, 2011

Listing MySQL functions and Procedures

Maintaining and updating stored procedures and functions in MySQL often will require root access which in practice means that you might need to have some interaction with your hosting provider if you wish to use them.

Operating the the standard phpMyAdmin interface gives no support for them other then the ability to create them through script.

The following bits of SQL are useful for viewing stored procedures and functions in a hosted database accessed through phpMyAdmin

SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE="FUNCTION"
AND ROUTINE_SCHEMA="database"

SELECT ROUTINE_NAME
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE="PROCEDURE"
AND ROUTINE_SCHEMA="database"


Also the "SHOW PROCEDURE STATUS" will give details of stored procedures and functions

Dealing with MySQL Function

Newer Versions of MySQL have the binary log which will generate te following error

This function has none of DETERMINISTIC, NO SQL, or READS SQL DATA in its declaration and binary logging is enabled (you *might* want to use the less safe log_bin_trust_function_creators variable)

To fix this you need incude the following keywords
  • CONTAINS SQL indicates that the routine does not contain statements that read or write data. This is the default if none of these characteristics is given explicitly. Examples of such statements are SET @x = 1 or DO RELEASE_LOCK('abc'), which execute but neither read nor write data.

  • NO SQL indicates that the routine contains no SQL statements.

  • READS SQL DATA indicates that the routine contains statements that read data (for example, SELECT), but not statements that write data.

  • MODIFIES SQL DATA indicates that the routine contains statements that may write data (for example, INSERT or DELETE).

Ther referenced artical indicates using
SET GLOBAL log_bin_trust_function_creators = 1;

References
http://mvnrepository.blogspot.com/2009/08/this-function-has-none-of-deterministic.html


Example
DELIMITER $$

DROP FUNCTION IF EXISTS `adadmin_adem`.`fDeleteTheme` $$
CREATE DEFINER=`root`@`localhost` FUNCTION `fDeleteTheme`(id_in INTEGER) RETURNS int(11)
DETERMINISTIC
READS SQL DATA
MODIFIES SQL DATA
BEGIN


DECLARE counter INTEGER;
DECLARE parent_id INTEGER;


SELECT count(id_theme) FROM s_themes where parent = id_in INTO counter;


IF counter = 0 THEN

SELECT parent FROM s_themes where id_theme = id_in INTO parent_id;
DELETE FROM adem.s_themes WHERE id_theme = id_in;
END IF;

RETURN parent_id;

END $$

DELIMITER ;

Tuesday, April 6, 2010

DLink 323 NAS box under Windows 7 or Vista

My D Link 323 NAS box worked perfectly under xp but with a dual upgrade to a Billton 7300 router and Windows 7 I have had continual problems.

After applying all the latest firmware to both devices I got it sorted

The final niggle was the 323 could be set up with mapped drives but I was randomly loosing my mapped drives when I shut it down. I could ping the NAS box and read the administration page and see the media server but could not access the file system via my mapped drives or device name ie \\NAS\Volume_1\

The solution turned out to be to use the ip address rather then the divice name in all mapping or accessing the device directly ie \\192.168.0.5\Volume_1\

This has been such a pain in the bottom I thought I would past it here - if someone is searching for the same problem they might pick it up.

Sunday, July 5, 2009

Return File name from path

Always handy - never there when you need it. A simple recursive function to return the file name from the full path


Private Function GetFilenameFromPath(ByVal strPath As String) As String
' Returns the rightmost characters of a string upto but not including the rightmost '\'
' e.g. 'c:\winnt\win.ini' returns 'win.ini'

If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function

Tuesday, April 14, 2009

List Object in SQL Db - Specific Examples

The generic SQL found here can be tweaked to do almost anything


The following are more specific examples
-- This snippet searches for columns named like %product% 
SELECT
o.name AS TableName,c.*
FROM
sysobjects AS o
INNER JOIN syscolumns AS c
ON c.id = o.id
WHERE
(o.type = 'U' OR o.type = 'S')
AND c.name LIKE '%product%'

Thursday, April 2, 2009

Deleting Restoring Databases

I keep forgetting this and it cost me time as the job runs forever and will not cancel.
With logshipping you sometimes need to delete a restoring database that has failed.
Remember that you need to uncheck the "delete backup and restore" checkbox


Tuesday, November 18, 2008

SQL- Strpping out time from DateTime - going back to weekdays

-- locate last sunday
DECLARE @Date As DATETIME
DECLARE @CurDay AS INTEGER

SET @CurDay = DATEPART(weekday,GETDATE())
SET @Date =
CASE
WHEN 1 = @CurDay THEN GETDATE()
WHEN 2 = @CurDay THEN DATEADD(DAY,-1,GETDATE())
WHEN 3 = @CurDay THEN DATEADD(DAY,-2,GETDATE())
WHEN 4 = @CurDay THEN DATEADD(DAY,-3,GETDATE())
WHEN 5 = @CurDay THEN DATEADD(DAY,-4,GETDATE())
WHEN 6 = @CurDay THEN DATEADD(DAY,-5,GETDATE())
WHEN 7 = @CurDay THEN DATEADD(DAY,-6,GETDATE())
ELSE GETDATE()
END
--Strip out the time part
SET @Date = CAST((STR( YEAR( GETDATE() ) ) + '/' + STR( MONTH( GETDATE() ) ) + '/' + STR( DAY( GETDATE() ) ) )AS DATETIME )
Print @Date

Avoid cursors in SQL Server with these methods to loop over records

This article copied from http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1339242,00.html?track=NL-414&ad=672066&asrc=EM_NLT_5051592&uid=6482800#

Matthew Schroeder
11.17.2008
Rating: --- (out of 5)


Digg This! StumbleUpon Toolbar StumbleUpon Bookmark with Delicious Del.icio.us










Many articles have beaten up on SQL Server cursors -- database objects that manipulate data in a set on a row-by-row basis -- and I want to add my name to the list of people who wish cursors had never been introduced. But, unfortunately, cursors are a fact of life. Problems with cursors include extending locks, their inability to cache execution plans and CPU/RAM overhead. Many T-SQL programmers and DBAs do not know how to successfully loop over records without the need for cursors. In this tip, I'll share some alternatives to cursors that provide looping functionality.

Method 1: Temp table with identity column

In the first approach, we will use a temp table with an identity column added to allow for row-by-row selection. If you're performing an INSERT/UPDATE/DELETE, be sure to use the explicit transactions. This vastly reduces the load on your log file by committing per loop, and it prevents huge rollbacks in the case of failure.

set nocount on
declare @i int
--iterator
declare @iRwCnt int
--rowcount
declare @sValue varchar(100)

set @i = 1
--initialize

create table #tbl(ID int identity(1,1), Value varchar(100))

insert into #tbl(Value)
select name
from master..sysdatabases (nolock)

set @iRwCnt = @@ROWCOUNT
--SCOPE_IDENTITY() would also work

create clustered index idx_tmp on #tbl(ID) WITH FILLFACTOR = 100
/*

Always do this after the insert, since it's faster to add the index in bulk than to update the index as you write into the temp table. Since you know the data in this column, you can set the fill factor to 100% to get the best read times.

*/
while @i <= @iRwCnt begin select @sValue = Value from #tbl where ID = @i
--begin tran
print 'My Value is ' + @sValue
--replace with your operations on this value
--commit tran

set @i = @i + 1
end
drop table #tbl

Method 2: Temp table without ID

In the second approach, we use a temp table without an identity column and simply grab the top row to process, then loop until we find no more rows to process. If you're performing an INSERT/UPDATE/DELETE, again, be sure to use the explicit transactions to vastly reduce the load on your log file by committing per loop, which prevents huge rollbacks in the case of failure.

set nocount on

declare @i int
--iterator
declare @iRwCnt int
--rowcount
declare @sValue varchar(100)
set @i = 1
--initialize

create table #tbl(Value varchar(100))

insert into #tbl(Value)
select name
from master..sysdatabases (nolock)

set @iRwCnt = @@ROWCOUNT
--SCOPE_IDENTITY() would also work

create clustered index idx_tmp on #tbl(Value) WITH FILLFACTOR = 100
/*

Always do this after the insert, since it's faster to add the index in bulk than to update the index as you write into the temp table. Since you know the data in this column, you can set the fill factor to 100% to get the best read times.

*/

while @iRwCnt > 0
begin
select top 1 @sValue = Value from #tbl
set @iRwCnt = @@ROWCOUNT
--ensure that we still have data

if @iRwCnt > 0
begin

--begin tran
print 'My Value is ' + @sValue --replace with your operations on this value
--commit tran

delete from #tbl where value = @sValue
--remove processed record
end
end

drop table #tbl

Method 3: Selecting a comma-delimited list of items

When most developers/DBAs are asked to come up with a list of comma-delimited values from a table, they typically use a cursor or temp table (as above) to loop through the records. However, if you do not need to use a GROUP BY or an ORDER BY, then you can use the method below that operates in batch to handle the task. This cannot be used with GROUP BY DISTINCT, or ORDER BY, because of how SQL Server handles those operations.

Basically, this takes a given variable, and for every row in the table it adds the current value to the variable along with a comma.

declare @vrs varchar(4000)
declare @sTbl sysname
set @sTbl = 'TableName'
set @vrs = ''
select @vrs = @vrs + ', ' + name from syscolumns where id = (select st.id from sysobjects as st where name = @sTbl) order by colorder
set @vrs = right(@vrs, len(@vrs)-2)
print @vrs

This article gives you some good reasons why cursors in SQL Server should be avoided as well as some alternatives that give you looping functionality. Keep in mind that SQL Server is designed around batch processing, so the less you loop, the faster your system will run.