<?xml version="1.0" encoding="utf-8"?>

			<rss version="2.0" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:cc="http://web.resource.org/cc/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">

			<channel>
			<title>Blog of Shaun McCran - Architecting robust, elegant technical and business solutions - SQL</title>
			<link>http://www.mccran.co.uk/index.cfm</link>
			<description>I write about Architecture and Design, Architectural patterns, Architectural Principles and Architectural policies. This includes TOGAF, Zachman, Business Architecture, SOA and Process and tools such as the IBM Rational software and Adobe products. I also write about my previous life as a mobile and web developer.</description>
			<language>en-gb</language>
			<pubDate>Tue, 09 Jun 2026 06:49:40 -0000</pubDate>
			<lastBuildDate>Sun, 03 Oct 2010 22:15:00 -0000</lastBuildDate>
			<generator>BlogCFC</generator>
			<docs>http://blogs.law.harvard.edu/tech/rss</docs>
			<managingEditor>shaun@mccran.co.uk</managingEditor>
			<webMaster>shaun@mccran.co.uk</webMaster>
			<itunes:subtitle></itunes:subtitle>
			<itunes:summary></itunes:summary>
			<itunes:category text="Technology" />
			<itunes:category text="Technology">
				<itunes:category text="Podcasting" />
			</itunes:category>
			<itunes:category text="Technology">
				<itunes:category text="Tech News" />
			</itunes:category>
			<itunes:keywords></itunes:keywords>
			<itunes:author></itunes:author>
			<itunes:owner>
				<itunes:email>shaun@mccran.co.uk</itunes:email>
				<itunes:name></itunes:name>
			</itunes:owner>
			
			<itunes:explicit>no</itunes:explicit>
			
			
			
			
			
			<item>
				<title>How to find out the size of data in MS SQL databases</title>
				<link>http://www.mccran.co.uk/index.cfm/2010/10/3/How-to-find-out-the-size-of-data-in-MS-SQL-databases</link>
				<description>
				
				If you are running Microsoft SQL server you may already be familiar with how the database file system can enlarge itself to astronomical proportions. There are &apos;Auto shrink&apos; and &apos;Auto grow&apos; options, but these are really not recommended for production environments.

So how do you go about determining how much space is being used by actual data IE records, and how much is being used by log files etc? This article will show you how to run a query that will return the size of all the tables in your database, and highlight a TSQL command that will clean up the file storage of a database.
				 [More]
				</description>
				
				
				<category>Development</category>
				
				<category>SQL</category>
				
				<pubDate>Sun, 03 Oct 2010 22:15:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2010/10/3/How-to-find-out-the-size-of-data-in-MS-SQL-databases</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>Returning values from mySQL in a select query as Yes/No rather than 1/0</title>
				<link>http://www.mccran.co.uk/index.cfm/2010/3/5/Returning-values-from-mySQL-in-a-select-query-as-YesNo-rather-than-10</link>
				<description>
				
				Whilst writing a ColdFusion based query to create a JSON response I thought I&apos;d look up returning data values as a &quot;Yes/No&quot; string rather than &quot;1/0&quot;. Then I wouldn&apos;t have to transform it in any way to use in the JSON build script.

The mySQL version allows you to do this by evaluating the value, and matching a string if the condition is met, like this:

&lt;code&gt;
SQL version: 
SELECT intid,varuserfname,varusersname, IF(intactive&lt;&gt;0, &quot;Yes&quot;, &quot;No&quot;)
FROM 	table.users
&lt;/code&gt;

This does not work in ColdFusion at all. An error is thrown:

&lt;img src=&quot;http://www.mccran.co.uk/images/cferror1.jpg&quot; /&gt;

After a little tweaking it seems that if you alias the field it does work. In the example code below I&apos;ve simply aliased the field with its own name.

I&apos;m not exactly clear why, as the error message above isn&apos;t all that helpful.

&lt;code&gt;
CF version:
SELECT intid,varuserfname,varusersname, IF(intactive&lt;&gt;0, &apos;Yes&apos;, &apos;No&apos;) as intactive
FROM 	table.users
&lt;/code&gt;
				
				</description>
				
				
				<category>Coldfusion</category>
				
				<category>SQL</category>
				
				<pubDate>Fri, 05 Mar 2010 11:48:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2010/3/5/Returning-values-from-mySQL-in-a-select-query-as-YesNo-rather-than-10</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>Emulating the mySql limit function in MS SQL</title>
				<link>http://www.mccran.co.uk/index.cfm/2010/2/15/Emulating-the-mySql-limit-function-in-MS-SQL</link>
				<description>
				
				There are pro&apos;s and con&apos;s to both mySql and MS SQL, one of the pro&apos;s of mySql is the limit function. This allows you to set a starting record number, and select &lt;i&gt;N&lt;/i&gt; number of records from there. But how can we do that in MS SQL? 

This is usually used for pagination functions, IE SELECT the next N records from the current count.

Firstly declare two variables, a &quot;rows per page&quot; and a start record.

&lt;code&gt;

&lt;cfset startpos = 10&gt;
&lt;cfset rowsperpage = 15&gt;

DECLARE @rowsperpage INT

            DECLARE @start INT

            SET @start = #startpos#
            SET @rowsperpage = #rows#

&lt;/code&gt;

Next we need to write the query we want, but wrap it in a parent select. Remember at this point to do all your conditional processing on the query inside the parenthesis.

&lt;code&gt;
SELECT * FROM

            (SELECT row_number() OVER (ORDER BY [intId]) AS rownum, *
                               
            FROM   [table]
                    Where [table].intId = &lt;cfqueryparam cfsqltype=&quot;cf_sql_integer&quot; value=&quot;#arguments.intId#&quot;&gt;) AS tempQuery

&lt;/code&gt;

Next we can apply a where clause that filters down the results based on the two variables declared at the top of the script. This means we will only get back the required number of records, starting at our defined record number.

&lt;code&gt;

Where tempQuery.rownum BETWEEN (@start) AND (@start + @rowsperpage) 
Order by rownum

&lt;/code&gt;

The whole script looks like this:

&lt;code&gt;

&lt;cfset startpos = 10&gt;
&lt;cfset rowsperpage = 15&gt;

DECLARE @rowsperpage INT

            DECLARE @start INT

            SET @start = #startpos#
            SET @rowsperpage = #rows#

SELECT * FROM

            (SELECT row_number() OVER (ORDER BY [intId]) AS rownum, *
                               
            FROM   [table]
                    Where [table].intId = &lt;cfqueryparam cfsqltype=&quot;cf_sql_integer&quot; value=&quot;#arguments.intId#&quot;&gt;) AS tempQuery

Where tempQuery.rownum BETWEEN (@start) AND (@start + @rowsperpage) 
Order by rownum

&lt;/code&gt;

I am selecting *, but I recommend that you actually list your fields here, I tweaked it for this entry. 

Not quite as nice as the mySql version tho is it:

&lt;code&gt;

Select *
From table
Limit 0,100

&lt;/code&gt;
				
				</description>
				
				
				<category>SQL</category>
				
				<pubDate>Mon, 15 Feb 2010 16:37:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2010/2/15/Emulating-the-mySql-limit-function-in-MS-SQL</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>Quotes being changed to question marks using cfsavecontent and MySql</title>
				<link>http://www.mccran.co.uk/index.cfm/2009/10/12/Quotes-being-changed-to-question-marks-using-cfsavecontent-and-MySql</link>
				<description>
				
				One of the tables in an online application stores entire html templates in a blob field, this data is pulled out and used to build emails, replacing specific keywords.

I recently needed to update some of this data, but there is not an administration system for it, so a manual SQL script would have to do.

The problem I encountered was that creating a html template as a variable using cfsavecontent and inserting it into MySql was causing all the &apos; to appear as ?. I read a &lt;a href=&quot; http://www.communitymx.com/content/article.cfm?page=3&amp;cid=B8723&quot; target=&quot;new&quot;&gt;blog entry&lt;/a&gt; based on Coldfusion MX and setting the character encoding in your coldfusion administrator, for each datasource. Or you could do it in the template, like this:

&lt;code&gt;
&lt;cfprocessingdirective pageencoding=&quot;iso-8859-1&quot;&gt;
&lt;cfcontent type=&quot;text/html; charset=iso-8859-1&quot;&gt;
&lt;/code&gt;

This didn&apos;t seem to work at all, in fact I found that it would error whilst trying to insert the cfsavecontent variable using cfqueryparam. There seemed to be some sort of encoding issue between the two tags.

&lt;code&gt;
&lt;cfsavecontent variable=&quot;htmlContent&quot;&gt;
Html template code
&lt;body&gt;  etc &lt;/body&gt;
&lt;/cfsavecontent&gt;
&lt;cfquery datasource=&quot;#application.dsn#&quot;&gt;
INSERT INTO table (fields)
VALUES (&apos;#htmlContent#&apos;);
&lt;/cfquery&gt;
&lt;/code&gt;

This didn&apos;t work either with Cfqueryparam, or as a non param input. It turns out that you simply need to escape the characters (double them, or use character representations). IE don&apos;t use a single quote, use two . In this way the MySql encoding treats the character as a character, rather than a potential command. I still think that this is something that can be fixed by setting the encoding type, but in this case there was a far simpler solution.
				
				</description>
				
				
				<category>Development</category>
				
				<category>Coldfusion</category>
				
				<category>SQL</category>
				
				<pubDate>Mon, 12 Oct 2009 12:32:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2009/10/12/Quotes-being-changed-to-question-marks-using-cfsavecontent-and-MySql</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>Example of inserting a Struct() into a database using keys</title>
				<link>http://www.mccran.co.uk/index.cfm/2009/8/26/Example-of-inserting-a-Struct-into-a-database-using-keys</link>
				<description>
				
				A while ago a colleague and I were working on a timesheet application in Flex. The idea was that you could commit a custom timebar object, generated in flex, and it would update the dataset in the back end using the ColdFusion flex gateway. 

I came across the code recently, and decided to tidy it up a bit, and make the query dynamic, based on the Struct contents. The obvious limitation to this is that your Struct and your database schema have to match exactly.

I won&apos;t go into the Flex application here, but I&apos;ve emulated its input arguments here with a pre-populated structure.

&lt;code&gt;
&lt;cfscript&gt;
      timesheetTask = StructNew();
      StructInsert(timesheetTask, &quot;employeeid&quot;, &apos;36&apos;);
      StructInsert(timesheetTask, &quot;timesheetDT&quot;, &apos;0&apos;);
      StructInsert(timesheetTask, &quot;projectid&quot;, &apos;6&apos;);
      StructInsert(timesheetTask, &quot;weekid&quot;, &apos;25&apos;);
      StructInsert(timesheetTask, &quot;taskid&quot;, &apos;39&apos;);
      StructInsert(timesheetTask, &quot;hours&quot;, &apos;8&apos;);
      StructInsert(timesheetTask, &quot;comment&quot;, &apos;Comments for this task live here&apos;);
      StructInsert(timesheetTask, &quot;szStatus&quot;, &apos;1&apos;);
      StructInsert(timesheetTask, &quot;iFirstLineApproval&quot;, &apos;23&apos;);
      StructInsert(timesheetTask, &quot;iSecondLineApproval&quot;, &apos;34&apos;);
      StructInsert(timesheetTask, &quot;iCurrentApprover&quot;, &apos;&apos;);
      StructInsert(timesheetTask, &quot;szRejectReason&quot;, &apos;&apos;);
      StructInsert(timesheetTask, &quot;szDescription&quot;, &apos;&apos;);
 
      updateTimesheet = createObject(&quot;component&quot;, &quot;timesheet&quot;);
      updateTimesheet.updateTask(timesheetTask);
&lt;/cfscript&gt;
&lt;/code&gt;

Notice that this code also calls the CFC object at the end. The data itself isn&apos;t massively important, it&apos;s a time object for recording tasks.

Next we have the function, which accepts a Struct() argument called &apos;taskStruct&apos;. I then loop through the structure, and populate a SQL query using the keys from a collection. The only logic is a check to see if it is the last structure element, as this controls the &apos;,&apos; placement.

 &lt;code&gt;
      &lt;cffunction name=&quot;updateTask&quot; access=&quot;remote&quot; returntype=&quot;string&quot; hint=&quot;Creates a record for timesheet tasks&quot;&gt;
            &lt;cfargument name=&quot;taskStruct&quot; type=&quot;struct&quot; required=&quot;yes&quot;&gt;
      &lt;cfset var count = 0&gt;

            &lt;cfdump var=&quot;#arguments.taskStruct#&quot;&gt;
      &lt;cfset variables.structSize = structCount(arguments.taskStruct)&gt;
 
      &lt;cfquery datasource=&quot;#application.dsn#&quot;&gt;
            INSERT INTO [dbo].[timesheet]
           (&lt;cfloop collection=&quot;#arguments.taskStruct#&quot; item=&quot;key&quot;&gt;
                        [#key#]
                        &lt;cfset count = count + 1&gt;
                        &lt;cfif count LT variables.structSize&gt;,&lt;/cfif&gt;
                  &lt;/cfloop&gt;)
    
      &lt;cfset count = 0&gt; 
      
      VALUES(&lt;cfloop collection=&quot;#arguments.taskStruct#&quot; item=&quot;key&quot;&gt;
                  &apos;#arguments.taskStruct[key]#&apos;
               &lt;cfset count = count + 1&gt;
               &lt;cfif count LT variables.structSize&gt;,&lt;/cfif&gt;
               &lt;/cfloop&gt;)
            &lt;/cfquery&gt;
 
            &lt;cfreturn true&gt;
      &lt;/cffunction&gt;
&lt;/code&gt;

That will insert your Struct into a database, in small and tidy manner. It was somewhere around here that we started using cfproperty tags, and creating strongly typed objects for Flex.
				
				</description>
				
				
				<category>Software Architecture</category>
				
				<category>Flex Remoting</category>
				
				<category>Coldfusion</category>
				
				<category>SQL</category>
				
				<pubDate>Wed, 26 Aug 2009 16:42:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2009/8/26/Example-of-inserting-a-Struct-into-a-database-using-keys</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>AIR Phone Book application - Part 1 (CFC and GUI)</title>
				<link>http://www.mccran.co.uk/index.cfm/2009/4/3/AIR-Phone-Book-application--Part-1-CFC-and-GUI</link>
				<description>
				
				I&apos;m always asking what peoples phone numbers are in the office, we currently don&apos;t have any internal communications (like an intranet) so I thought I&apos;d create a handy phone book application in AIR.

With FLEX of AIR applications I often wireframe them up with the data model in mind first. If you know what data you are going to display, and the format and delivery mechanism of that data, it can often have a large impact on the design and layout of your application.

In this instance I was just returning a simple query object of users and their phone numbers and a thumbnail image.

&lt;h3&gt;The CFC&lt;/h3&gt;

My preferred server language is ColdFusion, so my service is a CFC object.

&lt;code&gt;
&lt;cfcomponent hint=&quot;WLD phoneBook&quot; output=&quot;false&quot;&gt;

	&lt;cffunction name=&quot;getData&quot; access=&quot;remote&quot; hint=&quot;Gets phoneBook data&quot; returntype=&quot;query&quot;&gt;
	
		&lt;cfquery datasource=&quot;#application.dns#&quot; name=&quot;qGetPB&quot;&gt;
			select 	id AS ID, 
					name AS Name,
					number AS No,
					image As Image
			from phonebook 
			Order by name
		&lt;/cfquery&gt;

		&lt;cfreturn qGetPB&gt;
	&lt;/cffunction&gt;
	
&lt;/cfcomponent&gt;
&lt;/code&gt;

In my example I&apos;m using an MS SQL database, so I have included the creation script here:

&lt;code&gt;
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[phonebook](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[name] [varchar](20) NULL DEFAULT (NULL),
	[number] [int] NULL DEFAULT (NULL),
	[image] [varchar](55) NULL DEFAULT (NULL)
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
&lt;/code&gt;

Now that we know what the data will look like we can build the GUI front end.

My display layer is going to be a canvas, with another canvas inside it, to create a bordered effect.

Then I have a DataGrid, with a click event that will call an AS function. This will control the displaying of an image that corresponds to the user being clicked. Its always nice to see who you want to call!

&lt;code&gt;
&lt;mx:Fade id=&quot;fadeOut&quot; duration=&quot;1.0&quot; alphaFrom=&quot;1.0&quot; alphaTo=&quot;0.0&quot;/&gt;
&lt;mx:Fade id=&quot;fadeIn&quot; duration=&quot;2000&quot; alphaFrom=&quot;0.0&quot; alphaTo=&quot;1.0&quot;/&gt;
	&lt;mx:Canvas id=&quot;outerCanvas&quot; x=&quot;0&quot; y=&quot;0&quot; width=&quot;220&quot; height=&quot;240&quot; backgroundColor=&quot;#70c7f1&quot; borderStyle=&quot;solid&quot; cornerRadius=&quot;25&quot; borderThickness=&quot;0&quot;&gt;
	
		&lt;mx:Canvas id=&quot;innerCanvas&quot; x=&quot;10&quot; y=&quot;22&quot; width=&quot;200&quot; height=&quot;210&quot; backgroundColor=&quot;#FFFFFF&quot; borderStyle=&quot;solid&quot; cornerRadius=&quot;25&quot; borderThickness=&quot;0&quot;&gt;
			
			&lt;mx:Label x=&quot;10&quot; y=&quot;10&quot; text=&quot;White label&quot; id=&quot;header&quot; styleName=&quot;header&quot; fontWeight=&quot;bold&quot;/&gt;
			&lt;mx:Label x=&quot;78&quot; y=&quot;10&quot; text=&quot;Dating PhoneBook&quot; styleName=&quot;greyHeader&quot; fontWeight=&quot;bold&quot;/&gt;
			&lt;mx:DataGrid id=&quot;displayPeople&quot; x=&quot;10&quot; y=&quot;32&quot; width=&quot;180&quot; height=&quot;108&quot; itemClick=&quot;changeImage(displayPeople.selectedItem.IMAGE)&quot;&gt;
				&lt;mx:columns&gt;
					&lt;mx:DataGridColumn headerText=&quot;Name&quot; width=&quot;140&quot; dataField=&quot;NAME&quot;/&gt;
					&lt;mx:DataGridColumn headerText=&quot;No.&quot; width=&quot;40&quot; dataField=&quot;NO&quot;/&gt;
					&lt;mx:DataGridColumn headerText=&quot;Img&quot; width=&quot;40&quot; dataField=&quot;IMAGE&quot; visible=&quot;false&quot;/&gt;
				&lt;/mx:columns&gt;
			&lt;/mx:DataGrid&gt;
			&lt;mx:Image x=&quot;138&quot; y=&quot;150&quot; source=&quot;@Embed(source=&apos;wldLogoTiny.png&apos;)&quot; /&gt;
			&lt;mx:Image x=&quot;25&quot; y=&quot;144&quot; toolTip=&quot;{displayPeople.selectedItem.NAME}&quot; id=&quot;userImage&quot; visible=&quot;true&quot; showEffect=&quot;{fadeIn}&quot; /&gt;
		&lt;/mx:Canvas&gt;
		&lt;mx:Label text=&quot;_&quot; styleName=&quot;controls&quot; toolTip=&quot;Minimize&quot; x=&quot;173&quot; y=&quot;-2&quot; click=&quot;onMinimize()&quot; /&gt;
		&lt;mx:Label text=&quot;X&quot; styleName=&quot;controls&quot; toolTip=&quot;Close&quot; x=&quot;184&quot; y=&quot;1&quot; click=&quot;onClose()&quot; /&gt;

	&lt;/mx:Canvas&gt;
&lt;/code&gt;

My &apos;userImage&apos;has a showEffect attribute, that uses an image fadeIn method. It fades in the first image called, but not any others, I&apos;ve had a play around with this, and I can&apos;t get it to fade in subsequent images, so if anyone has any ideas let me know!

Lastly I have added some chrome controls, as I will be removing the standard chrome, and building my own.

Now, on to the &lt;a href=&quot;http://www.mccran.co.uk/index.cfm/2009/4/3/AIR-Phone-Book-application--Part-2-Functions-and-WebService&quot;&gt;functions&lt;/a&gt;.
				
				</description>
				
				
				<category>Flex Remoting</category>
				
				<category>Coldfusion</category>
				
				<category>AIR</category>
				
				<category>SQL</category>
				
				<category>RIA</category>
				
				<pubDate>Fri, 03 Apr 2009 14:46:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2009/4/3/AIR-Phone-Book-application--Part-1-CFC-and-GUI</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>SQL Stored Procedures, UPDATE Template script</title>
				<link>http://www.mccran.co.uk/index.cfm/2009/3/17/SQL-Stored-Procedures-UPDATE-Template-script</link>
				<description>
				
				This article deals with creating a SQL stored procedure for Updating a record.

In each of these stored procedure templates I am declaring a variety of documentation parameters in the header.

I&apos;ve found these handy in the past when you are working in a team environment, or when you go back to a procedure at a later date. 
Its much easier to read a simple description in the header, than trawl through the SQL code looking for what it is doing.

So, this declares the procedure name, any parameters and return codes, and also details what it does, and who made it.

In a modified version of this I also hold the SVN revision number here.

&lt;code&gt;

/********************************************************************************/
/*		              Company Name                   							*/
/********************************************************************************/
/*      Procedure Name  : dbo.ssp_stored_procname                               */
/*      Parameters      :                                                       */
/*      Return Codes    :                                                       */
/*                                                                              */
/*      Description     : Description of what it does, params etc               */
/*                                                                              */
/*                                                                              */
/*                                                                              */
/*                                                                              */
/*                                                                              */
/*      Author          : Authorname                                            */
/*      Date written    : Date                                                  */
/*      History         : version number                                        */
/*                                                                              */
/********************************************************************************/

&lt;/code&gt;

The next block of code performs a select on the sysObjects table (part of the Master database). It is checking for the existence of itself.
If it finds itself, it will drop the procedure. Note that throughout all of these scripts we are telling the user at each stage what is going on, by printing useful english output back to the screen.

&lt;code&gt;

IF EXISTS (SELECT 1 FROM sysobjects where id = object_id(&apos;dbo.ssp_stored_procname&apos;) and sysstat &amp; 0xf = 4)
BEGIN
	PRINT &apos;Dropping old version of dbo.ssp_stored_procname&apos;
	DROP PROCEDURE dbo.ssp_stored_procname
END
GO

&lt;/code&gt;

By now we have identified whether or not the procedure previously existed, and if it did, we have dropped it, so we know that we are all good to go.
So to create our Update procedure, we print out a message to the user, then using the &quot;CREATE PROCEDURE&quot; command we create our procedure.

At this point you substitute the &quot;@field&quot; value with your field name, and the [datatype] and (datasize) with the correct values. 
Just list your fields one after another, seperating with a comma. As this is creating an Update stored procedure I will list any of the values to update in the query here.
&lt;code&gt;

PRINT &apos;Creating procedure dbo.ssp_stored_procname - START&apos;
GO
 
CREATE PROCEDURE dbo.ssp_stored_procname
	(@field 		[datatype](datasize),
	 @field 		[datatype],
	 @field		[datatype](datasize),
	 @field		[datatype](datasize),
	 @field		[datatype],
	 @field		[datatype])
&lt;/code&gt;

After that we create the SQL code, as per usual. We have an Update statement, using the variables declared above in the SQL variable declaration (@var).  Just write out your update like you normally would here.
Then we check for any errors, and return a success message if it all worked ok!

&lt;code&gt;
AS UPDATE tablename 
SET  [field]	 = @field, 
     [field]	 = @field,
     [field]	 = @field,
     [field]	 = @field,
     [field]	 = @field
WHERE 
	( [field] = @conditions)
RETURN @@ERROR
GO
PRINT &apos;Creating procedure dbo.ssp_stored_procname - END&apos;
GO
&lt;/code&gt;
By using a script like this I&apos;ve found that its really simple to have a repeatable standard process that is easy to implement across a team of developers,
ensuring you get the same results, no matter who writes the query. It is also very useful if you have a seperate implementation team, as these scripts are re-runnable, they clear up after themselves.

Download the full template &lt;a href=&quot;http://www.mccran.co.uk/SQLSSPUpdateStatementTemplate.cfm&quot; target=&quot;new&quot;&gt;here&lt;/a&gt;.
				
				</description>
				
				
				<category>Software Architecture</category>
				
				<category>Best practices</category>
				
				<category>SQL</category>
				
				<pubDate>Tue, 17 Mar 2009 12:46:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2009/3/17/SQL-Stored-Procedures-UPDATE-Template-script</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>SQL Stored Procedures, DELETE Template script</title>
				<link>http://www.mccran.co.uk/index.cfm/2009/3/11/SQL-Stored-Procedures-DELETE-Template-script</link>
				<description>
				
				This article deals with creating a SQL stored procedure for deleting a record.

In each of these stored procedure templates I am declaring a variety of documentation parameters in the header.

I&apos;ve found these handy in the past when you are working in a team environment, or when you go back to a procedure at a later date. 
Its much easier to read a simple description in the header, than trawl through the SQL code looking for what it is doing.

So, this declares the procedure name, any parameters and return codes, and also details what it does, and who made it.

In a modified version of this I also hold the SVN revision number here.

&lt;code&gt;

/********************************************************************************/
/*		              Company Name                   							*/
/********************************************************************************/
/*      Procedure Name  : dbo.ssp_stored_procname                               */
/*      Parameters      :                                                       */
/*      Return Codes    :                                                       */
/*                                                                              */
/*      Description     : Description of what it does, params etc               */
/*                                                                              */
/*                                                                              */
/*                                                                              */
/*                                                                              */
/*                                                                              */
/*      Author          : Authorname                                            */
/*      Date written    : Date                                                  */
/*      History         : version number                                        */
/*                                                                              */
/********************************************************************************/

&lt;/code&gt;

The next block of code performs a select on the sysObjects table (part of the Master database). It is checking for the existence of itself.
If it finds itself, it will drop the procedure. Note that throughout all of these scripts we are telling the user at each stage what is going on, by printing useful english output back to the screen.

&lt;code&gt;

IF EXISTS (SELECT 1 FROM sysobjects where id = object_id(&apos;dbo.ssp_stored_procname&apos;) and sysstat &amp; 0xf = 4)
BEGIN
	PRINT &apos;Dropping old version of dbo.ssp_stored_procname&apos;
	DROP PROCEDURE dbo.ssp_stored_procname
END
GO

&lt;/code&gt;

By now we have identified wether or not the procedure previously existed, and if it did, we have dropped it, so we know that we are all good to go.
So to create our Insert procedure, we print out a message to the user, then using the &quot;CREATE PROCEDURE&quot; command we create our procedure.

At this point you substitute the &quot;@field&quot; value with your field name, and the [datatype] and (datasize) with the correct values. 
Just list your fields one after another, seperating with a comma. As this is creating a delete stored procedure I will only be inserting one variable into the query.
&lt;code&gt;

PRINT &apos;Creating procedure dbo.ssp_stored_procname - START&apos;
GO
 
CREATE PROCEDURE dbo.ssp_stored_procname
	(@field			[datatype](datasize))
&lt;/code&gt;

After that we create the SQL code, as per usual. We have a Delete statement, using the variable declared above in the SQL variable declaration (@var).  Just write out your delete like you normally would here.
Then we check for any errors, and return a success message if it all worked ok!

&lt;code&gt;
DELETE FROM table
WHERE (conditions = @var)
RETURN @@ERROR
GO

PRINT &apos;Creating procedure dbo.ssp_stored_procname - END&apos;
GO

&lt;/code&gt;

By using a script like this I&apos;ve found that its really simple to have a repeatable standard process that is easy to implement across a team of developers,
ensuring you get the same results, no matter who writes the query. It is also very useful if you have a seperate implementation team, as these scripts are 
re-runnable, they clear up after themselves.

Download the full template &lt;a href=&quot;SQLSSPDeleteStatementTemplate.cfm&quot; target=&quot;new&quot;&gt;here&lt;/a&gt;.
				
				</description>
				
				
				<category>Software Architecture</category>
				
				<category>SQL</category>
				
				<pubDate>Wed, 11 Mar 2009 15:59:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2009/3/11/SQL-Stored-Procedures-DELETE-Template-script</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>SQL Stored Procedures, SELECT Template script</title>
				<link>http://www.mccran.co.uk/index.cfm/2009/3/10/SQL-Stored-Procedures-SELECT-Template-script</link>
				<description>
				
				This article deals with creating a SQL stored procedure for selecting a record.

In each of these stored procedure templates I am declaring a variety of documentation parameters in the header.

I&apos;ve found these handy in the past when you are working in a team environment, or when you go back to a procedure at a later date. 
Its much easier to read a simple description in the header, than trawl through the SQL code looking for what it is doing.

So, this declares the procedure name, any parameters and return codes, and also details what it does, and who made it.

In a modified version of this I also hold the SVN revision number here.

&lt;code&gt;

/********************************************************************************/
/*		              Company Name                   							*/
/********************************************************************************/
/*      Procedure Name  : dbo.ssp_stored_procname                               */
/*      Parameters      :                                                       */
/*      Return Codes    :                                                       */
/*                                                                              */
/*      Description     : Description of what it does, params etc               */
/*                                                                              */
/*                                                                              */
/*                                                                              */
/*                                                                              */
/*                                                                              */
/*      Author          : Authorname                                            */
/*      Date written    : Date                                                  */
/*      History         : version number                                        */
/*                                                                              */
/********************************************************************************/

&lt;/code&gt;

The next block of code performs a select on the sysObjects table (part of the Master database). It is checking for the existence of itself.
If it finds itself, it will drop the procedure. Note that throughout all of these scripts we are telling the user at each stage what is going on, by printing 
useful english output back to the screen.

&lt;code&gt;

IF EXISTS (SELECT 1 FROM sysobjects where id = object_id(&apos;dbo.ssp_stored_procname&apos;) and sysstat &amp; 0xf = 4)
BEGIN
	PRINT &apos;Dropping old version of dbo.ssp_stored_procname&apos;
	DROP PROCEDURE dbo.ssp_stored_procname
END
GO

&lt;/code&gt;

By now we have identified wether or not the procedure previously existed, and if it did, we have dropped it, so we know that we are all good to go.
So to create our Insert procedure, we print out a message to the user, then using the &quot;CREATE PROCEDURE&quot; command we create our procedure.

At this point you substitute the &quot;@field&quot; value with your field name, and the [datatype] and (datasize) with the correct values. 
As an example of this the first line in this proc will create a field named &apos;varName&apos; with a data type of varchar with a character limit of 100.
Just list your fields one after another, seperating with a comma.

&lt;code&gt;

PRINT &apos;Creating procedure dbo.ssp_stored_procname - START&apos;
GO
 
CREATE PROCEDURE dbo.ssp_stored_procname
	(varName		[varchar](100),
	 @field	 		[int],
	 @field			[datatype](datasize),
	 @field			[datatype],
	 @field			[datatype],
	 @field			[datatype])


&lt;/code&gt;

After that we create the SQL code, as per usual. We have a Select statement, listing the fields, and the SQL variable declaration (@var). 
Then we check for any errors, and return a success message if it all worked ok!

&lt;code&gt;
Select Fields
from   Table
Where  (Conditions)
RETURN @@ERROR
GO

PRINT &apos;Creating procedure dbo.ssp_stored_procname - END&apos;
GO

&lt;/code&gt;

By using a script like this I&apos;ve found that its really simple to have a repeatable standard process that is easy to implement across a team of developers,
ensuring you get the same results, no matter who writes the query. It is also very useful if you have a seperate implementation team, as these scripts are 
re-runnable, they clear up after themselves.

Download the full template &lt;a href=&quot;SQLSSPSelectStatementTemplate.cfm&quot; target=&quot;new&quot;&gt;here&lt;/a&gt;.
				
				</description>
				
				
				<category>Software Architecture</category>
				
				<category>Best practices</category>
				
				<category>SQL</category>
				
				<pubDate>Tue, 10 Mar 2009 14:29:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2009/3/10/SQL-Stored-Procedures-SELECT-Template-script</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>SQL Stored Procedures, INSERT Template script</title>
				<link>http://www.mccran.co.uk/index.cfm/2009/3/4/SQL-Stored-Procedures-INSERT-Template-script</link>
				<description>
				
				This article deals with creating a SQL stored procedure for inserting a record.

In each of these stored procedure templates I am declaring a variety of documentation parameters in the header.

I&apos;ve found these handy in the past when you are working in a team environment, or when you go back to a procedure at a later date. 
Its much easier to read a simple description in the header, than trawl through the SQL code looking for what it is doing.

So, this declares the procedure name, any parameters and return codes, and also details what it does, and who made it.

In a modified version of this I also hold the SVN revision number here.

&lt;code&gt;

/********************************************************************************/
/*		              Company Name                   							*/
/********************************************************************************/
/*      Procedure Name  : dbo.ssp_stored_procname                               */
/*      Parameters      :                                                       */
/*      Return Codes    :                                                       */
/*                                                                              */
/*      Description     : Description of what it does, params etc               */
/*                                                                              */
/*                                                                              */
/*                                                                              */
/*                                                                              */
/*                                                                              */
/*      Author          : Authorname                                            */
/*      Date written    : Date                                                  */
/*      History         : version number                                        */
/*                                                                              */
/********************************************************************************/

&lt;/code&gt;

The next block of code performs a select on the sysObjects table (part of the Master database). It is checking for the existence of itself.
If it finds itself, it will drop the procedure. Note that throughout all of these scripts we are telling the user at each stage what is going on, by printing 
useful english output back to the screen.

&lt;code&gt;

IF EXISTS (SELECT 1 FROM sysobjects where id = object_id(&apos;dbo.ssp_stored_procname&apos;) and sysstat &amp; 0xf = 4)
BEGIN
	PRINT &apos;Dropping old version of dbo.ssp_stored_procname&apos;
	DROP PROCEDURE dbo.ssp_stored_procname
END
GO

&lt;/code&gt;

By now we have identified wether or not the procedure previously existed, and if it did, we have dropped it, so we know that we are all good to go.
So to create our Insert procedure, we print out a message to the user, then using the &quot;CREATE PROCEDURE&quot; command we create our procedure.

At this point you substitute the &quot;@field&quot; value with your field name, and the [datatype] and (datasize) with the correct values. 
As an example of this the first line in this proc will create a field named &apos;varName&apos; with a data type of varchar with a character limit of 100.
Just list your fields one after another, seperating with a comma.

&lt;code&gt;

PRINT &apos;Creating procedure dbo.ssp_stored_procname - START&apos;
GO
 
CREATE PROCEDURE dbo.ssp_stored_procname
	(varName		[varchar](100),
	 @field	 		[int],
	 @field			[datatype](datasize),
	 @field			[datatype],
	 @field			[datatype],
	 @field			[datatype])


&lt;/code&gt;

After that we create the SQL code, as per usual. We have an Insert statement, listing the fields, and the SQL variable declaration (@var). 
Then we check for any errors, and return a success message if it all worked ok!

&lt;code&gt;

AS INSERT INTO table
	 ([field],
	  [field],
	  [field],
	  [field],
	  [field],
	  [field])
VALUES
	(@field,
	 @field,
	 @field,
	 @field,
	 @field,
	 @field)

RETURN @@ERROR
GO

PRINT &apos;Creating procedure dbo.ssp_stored_procname - END&apos;
GO

&lt;/code&gt;

By using a script like this I&apos;ve found that its really simple to have a repeatable standard process that is easy to implement across a team of developers,
ensuring you get the same results, no matter who writes the query. It is also very useful if you have a seperate implementation team, as these scripts are 
re-runnable, they clear up after themselves.

Download the full template &lt;a href=&quot;SQLSSPInsertStatementTemplate.cfm&quot; target=&quot;new&quot;&gt;here&lt;/a&gt;.
				
				</description>
				
				
				<category>Software Architecture</category>
				
				<category>Best practices</category>
				
				<category>SQL</category>
				
				<pubDate>Wed, 04 Mar 2009 11:08:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2009/3/4/SQL-Stored-Procedures-INSERT-Template-script</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>MS SQL Stored procedure templates</title>
				<link>http://www.mccran.co.uk/index.cfm/2009/3/2/MS-SQL-Stored-procedure-templates</link>
				<description>
				
				Over the course of working with one employer, I headed up an investigation into our current server performance, and how would could potentially aim for at least a 25% to 30% increase on our current user thresholds before our capacity maxed out.

After looking through a series of server logs, and data transactions it was easy to see that the server technology being used, Coldfusion, is not the most efficient data handler in the world.

So after stripping back our application layer, taking a peek under the hood, and changing around 600 or so instances of data connectivity from inline SQL code, to Stored Procedures, we had more than exceeded our target gain. In fact under stress testing we had achieved a consistent increase of around 65% threshold. As a quick set of figures, the server loads had changed from CF, running at 75%-80% dropping to 20%-25%, and SQL server running at 6% increased to around 15%.

Based on these figures, and architectural methodologies I&apos;ve learnt since, I would always recommend stored procedures over inline SQL code. This has lead me to develop a standard set of SQL templates for developers to use. 

They are self checking, repeatable SQL templates that will action the desired changes, and check for any existing conditions up front. The idea is that a non technical resource could run them, and receive a useable English response.

1.	&lt;a href=&quot;http://www.mccran.co.uk/index.cfm/2009/3/10/SQL-Stored-Procedures-SELECT-Template-script&quot;&gt;Select statement&lt;/a&gt;&lt;br/&gt;
2.	
&lt;a href=&quot;http://www.mccran.co.uk/index.cfm/2009/3/17/SQL-Stored-Procedures-UPDATE-Template-script&quot;&gt;Update Statement&lt;/a&gt;&lt;br/&gt;
3.	&lt;a href=&quot;http://www.mccran.co.uk/index.cfm/2009/3/4/SQL-Stored-Procedures-INSERT-Template-script&quot;&gt;Insert statement&lt;/a&gt;&lt;br/&gt;
4.	
&lt;a href=&quot;http://www.mccran.co.uk/index.cfm/2009/3/11/SQL-Stored-Procedures-DELETE-Template-script&quot;&gt;Delete statement&lt;/a&gt;&lt;br/&gt;
				
				</description>
				
				
				<category>Software Architecture</category>
				
				<category>Coldfusion</category>
				
				<category>Best practices</category>
				
				<category>SQL</category>
				
				<pubDate>Mon, 02 Mar 2009 12:10:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2009/3/2/MS-SQL-Stored-procedure-templates</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>Differences between cfQueryParam &quot;cf_sql_date&quot; and &quot;cf_sql_timestamp&quot;</title>
				<link>http://www.mccran.co.uk/index.cfm/2009/2/26/Differences-between-cfQueryParam-cfsqldate-and-cfsqltimestamp</link>
				<description>
				
				I was recently looking at a report generator, and came across a conflict in the mySql query dealing with the date objects.

The report returns a set of records between two dates, using cfqueryparam, but there seemed to be a problem in running the query using certain dates. 

Running it from a browser provided differing results from running it directly in a sql interface. So where was the error?

The original code was using the &quot;cf_sql_date&quot; type to pass the date time off to the sql engine. It appears that this data type is not transferred as a date time value, but as an incompatible numeric value, that is not comparable to the mySql datetime I am querying against.

&lt;code&gt;
AND table.ap_startdate &gt;= &lt;cfqueryparam cfsqltype=&quot;CF_SQL_DATE&quot; value=&quot;#createodbcdate(arguments.rangefrom)#&quot;&gt;

AND table.ap_enddate &lt;= &lt;cfqueryparam cfsqltype=&quot;CF_SQL_DATE&quot; value=&quot;#createodbcdate(arguments.rangeto)#&quot;&gt;

&lt;/code&gt;

There are a wealth of articles online about passing date values into a variety of database technologies, but this Adobe post was very helpful.

&lt;a href=http://livedocs.adobe.com/coldfusion/7/htmldocs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=ColdFusion_Documentation&amp;file=00000317.htm&quot; target=&quot;new_win&quot;&gt;This article&lt;/a&gt; shows a handy table of cfsqltypes and how they map to different database management systems.

Using something like sql profiler you can clearly see the difference between cf_sql_date and cf_sql_timestamp, where cf_sql_date is being truncated to just a date value (actually evaluates as a numeric value) and a full date time stamp that cf_sql_timestamp generates.

&lt;code&gt;
AND table.ap_startdate &gt;= &lt;cfqueryparam cfsqltype=&quot;cf_sql_timestamp&quot; value=&quot;#createodbcdate(arguments.rangefrom)#&quot;&gt;

AND table.ap_enddate &lt;= &lt;cfqueryparam cfsqltype=&quot;cf_sql_timestamp&quot; value=&quot;#createodbcdate(arguments.rangeto)#&quot;&gt;

&lt;/code&gt;

Changing the code to the above example completely resolves this issue.
				
				</description>
				
				
				<category>Coldfusion</category>
				
				<category>SQL</category>
				
				<pubDate>Thu, 26 Feb 2009 18:10:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2009/2/26/Differences-between-cfQueryParam-cfsqldate-and-cfsqltimestamp</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>Mysql left and right functions</title>
				<link>http://www.mccran.co.uk/index.cfm/2009/2/4/Mysql-left-and-right-functions</link>
				<description>
				
				When you need to extract specific elements from a column, MySQL has a few functions that can help. I&apos;ve always found it much easier to provide the data to your application layer in the corrct format in the first place, rather than excessive processing in GUI layer.

Suppose I needed to check that column in the table always has a trailing &apos;/&apos; on the column data.

&lt;code&gt;
select 	id, 
	name, 
	RIGHT(url, 1) as slash
	from table
	where RIGHT(url, 1) != &quot;/&quot;
&lt;/code&gt;

In the LEFT() function, using the column telephone along with the number of characters to extract, starting from the first character on the left in the column. 
&lt;p&gt;
The RIGHT() function is similar, but it starts from the last character on the right, counting left to encapsulate the last seven characters. &lt;br/&gt;In the SQL statement below, areaCode is reused to order the results set. To reformat the telephone number, it will be necessary to use the SUBSTRING() function.

&lt;code&gt;
   SELECT LEFT(telephone, 3) AS areaCode,
   RIGHT(telephone, 7) AS telNo
   FROM contacts
   ORDER BY areaCode;

   SELECT CONCAT(&apos;(&apos;, LEFT(telephone, 3), &apos;) &apos;,
   SUBSTRING(telephone, 4, 3), &apos;-&apos;,
   MID(telephone, 7)) AS &apos;Telephone Number&apos;
   FROM contacts
   ORDER BY LEFT(telephone, 3);
&lt;/code&gt;
				
				</description>
				
				
				<category>SQL</category>
				
				<pubDate>Wed, 04 Feb 2009 12:18:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2009/2/4/Mysql-left-and-right-functions</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>Coldfusion Server connectiong to SQL Server Express 2005</title>
				<link>http://www.mccran.co.uk/index.cfm/2009/2/2/Coldfusion-Server-connectiong-to-SQL-Server-Express-2005</link>
				<description>
				
				I&apos;ve been using SQL Server Express for quite a while noa, and still prefer it to almost every other database application. I was rebuilding a development environment the other day, and discovered that I was using an ODBC &quot;trusted connection&quot; to connect to a SQL Server instance in Coldfusion Server. Why was this I thought?

It turns out that I&apos;d had some problems getting Coldfusion to connect SQL Server datasource connection, so I&apos;d used a custom ODBC connection. Looking into the connection error and having a dig around I found out a few things its worth checking when installing SQL Server.

&lt;img src=&quot;http://www.mccran.co.uk/images/images//SQLServer2005Logo.jpg&quot;&gt;

1. First thing is to enable TCP/IP connectivity, as its not on by default. Go to Start -&gt; All Programs -&gt; Microsoft SQL Server 2005 -&gt; Configuration Tools -&gt; SQL Server Configuration Manager. 
Under SQL Server 2005 Network Configuration, click on Protocols for SQLEXPRESS, click on TCP/IP, and click enable. Then restart the service, which you can do from the Configuration Manager under the SQL Server 2005 Services area, or in windows services.

2. In my experience SQL Server always used to use port 1433 by default after installation. For some reason it hadn&apos;t used this port, it was using 1523. I was quite puzzled about this as I just used accepted the installation defaults. The port is a crucial setting when you&apos;re setting up your datasources for Coldfusion, otherwise CF wont even find the datasource, let alone attempt to connect. To check your port number, go to the SQL Server Configuration Manager, go to Network Configuration/Protocols again, right click on TCP/IP, choose Properties, then click on the IP Addresses tab. Look under IPAll in the TCP Dynamic Ports section. I personally wouldn&apos;t change this as I&apos;m not really sure why SQL Server is using a different port now. I just used it in my Coldfusion datasource setup, and it connected fine.
				
				</description>
				
				
				<category>Coldfusion</category>
				
				<category>SQL</category>
				
				<pubDate>Mon, 02 Feb 2009 17:01:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2009/2/2/Coldfusion-Server-connectiong-to-SQL-Server-Express-2005</guid>
				
				
			</item>
			
		 	
			
			
			<item>
				<title>Using LIMIT in mySql Update script</title>
				<link>http://www.mccran.co.uk/index.cfm/2009/1/14/Using-LIMIT-in-mySql-Update-script</link>
				<description>
				
				I&apos;ve recently switched to MySql, as my present employer uses it.

Its taken a bit of getting used to, but I&apos;m coming around to it.

One piece of functionality we have is a &apos;queue-ing&apos; system. There is an image queue that users have to go through to &apos;vet&apos; photos. In this instance of work I needed to update a collection of records. It didn&apos;t matter which ones, just enough to fill the queue.

&lt;code&gt;
UPDATE tableName
SET active = 0
LIMIT 500;
&lt;/code&gt;

So rather than using a where clause it seems that you can use a mySql LIMIT value, to just return a set number of records.

Simple but effective.
				
				</description>
				
				
				<category>SQL</category>
				
				<pubDate>Wed, 14 Jan 2009 14:03:00 -0000</pubDate>
				<guid>http://www.mccran.co.uk/index.cfm/2009/1/14/Using-LIMIT-in-mySql-Update-script</guid>
				
				
			</item>
			
		 	
			</channel></rss>