I use the SyntaxHighlighter Evolved plugin for WordPress to format and highlight my code snippets. The plugin uses the SyntaxHighlighter JavaScript package by Alex Gorbatchev, and it’s accompanying java script files, called ‘brushes’, to highlight many different programming languages. While it is possible to register new brush files for additional languages, I decided to modify an existing file for simplicity’s sake.

Being that I work mostly with SQL Server, I decided to tailor the ‘shBrushSql.js’ file specifically for T-SQL. I started by looking for lists of the SQL 2008 built-in functions, which I found a good copy of at sql2008.info. Next was the reserved keywords, which i pulled from a MSDN BOL article for SQL Server 2008. Lastly, I compiled the list of text operators from a few sources, and made sure there were no duplicates between lists. The final enhancement was to update the RegEx statement to better handle comments. I am by no means a RegEx expert, more like a newbie, but I found this current statement to work on all of my tested comments.

Code for the updated ‘shBrushSql.js’ file is below.

/**
 * SyntaxHighlighter
 * http://alexgorbatchev.com/
 *
 * SyntaxHighlighter is donationware. If you are using it, please donate.
 * http://alexgorbatchev.com/wiki/SyntaxHighlighter:Donate
 *
 * @version
 * 2.1.364 (October 15 2009)
 *
 * @copyright
 * Copyright (C) 2004-2009 Alex Gorbatchev.
 *
 * @license
 * This file is part of SyntaxHighlighter.
 *
 * SyntaxHighlighter is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SyntaxHighlighter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SyntaxHighlighter. If not, see <http://www.gnu.org/copyleft/lesser.html>.
 */
SyntaxHighlighter.brushes.Sql = function()
{
	var funcs	=	'abs acos app_name ascii asin assemblyproperty asymkey_id '+
					'asymkeyproperty atan atn2 avg case cast convert ceiling cert_id char '+
					'charindex checksum_agg coalesce col_length col_name collationproperty '+
					'columnproperty columns_updated containstable cos cot count count_big '+
					'current_timestamp current_user '+
					'database_principal_id databaseproperty databasepropertyex datalength '+
					'dateadd datediff datename datepart day db_id db_name degrees dense_rank '+
					'difference error_line error_message error_number error_procedure '+
					'error_severity error_state exp file_id file_idex file_name filegroup_id '+
					'filegroup_name filegroupproperty fileproperty floor fn_helpcollations '+
					'fn_listextendedproperty fn_my_permissions '+
					'fn_virtualfilestats formatmessage freetexttable fulltextcatalogproperty '+
					'fulltextserviceproperty getansinull getdate getutcdate grouping '+
					'has_perms_by_name host_id host_name ident_current ident_incr ident_seed '+
					'identity index_col indexkey_property indexproperty is_member '+
					'is_srvrolemember isdate isnull isnumeric key_guid key_id key_name '+
					'left len log log10 lower ltrim max min month nchar newid ntile nullif '+
					'object_definition object_id object_name object_schema_name '+
					'objectproperty objectpropertyex opendatasource openquery openrowset '+
					'openxml original_login parsename patindex pi '+
					'power pwdcompare pwdencrypt quotename radians rand rank replace '+
					'replicate reverse right round row_number rowcount_big rtrim '+
					'schema_id schema_name scope_identity serverproperty '+
					'session_user sessionproperty setuser sign sin soundex space '+
					'sql_variant_property sqrt square stats_date stdev stdevp str stuff '+
					'substring sum suser_id suser_name suser_sid suser_sname symkeyproperty '+
					'fn_builtin_permissions sysdatetime sysdatetimeoffset '+
					'system_user sysutcdatetime tan textptr textvalid type_id type_name '+
					'typeproperty unicode upper user_id user_name user_name var varp '+
					'xact_state year';

	var keywords =	'add alter as asc authorization backup begin '+
					'break browse bulk by cascade check checkpoint '+
					'close clustered collate column commit compute '+
					'constraint contains continue create '+
					'current current_date current_time '+
					'cursor database dbcc deallocate declare default delete deny '+
					'desc disk distinct distributed double drop dump else end '+
					'errlvl escape except exec execute exit external fetch '+
					'file fillfactor for foreign freetext from full '+
					'function goto grant group having holdlock '+
					'identity_insert identitycol if index insert intersect '+
					'into is key kill lineno load merge national '+
					'nocheck nonclustered of off offsets on open '+
					'option order '+
					'over percent pivot plan precision primary print proc '+
					'procedure public raiserror read readtext reconfigure references '+
					'replication restore restrict return revert revoke rollback '+
					'rowcount rowguidcol rule save schema securityaudit select '+
					'set shutdown statistics '+
					'table tablesample textsize then to top tran transaction trigger '+
					'truncate tsequal union unique unpivot update updatetext use '+
					'user values varying view waitfor when where while with '+
					'bigint bit decimal int money numeric smallint smallmoney tinyint '+
					'float real date datetimeoffset datetime2 smalldatetime datetime time '+
					'binary image varbinary hierarchyid sql_variant timestamp uniqueidentifier xml';

	var operators =	'all and any between exists cross in inner join like not null or outer some';

	this.regexList = [
		{ regex: /([/]\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+[/])|(--.*)/gm, css: 'comments' },			// one line and multiline comments
		{ regex: SyntaxHighlighter.regexLib.multiLineDoubleQuotedString,	css: 'string' },			// double quoted strings
		{ regex: SyntaxHighlighter.regexLib.multiLineSingleQuotedString,	css: 'string' },			// single quoted strings
		{ regex: new RegExp(this.getKeywords(funcs), 'gmi'),				css: 'color2' },			// functions
		{ regex: new RegExp(this.getKeywords(operators), 'gmi'),			css: 'color1' },			// operators and such
		{ regex: new RegExp(this.getKeywords(keywords), 'gmi'),				css: 'keyword' }			// keyword
		];
};

SyntaxHighlighter.brushes.Sql.prototype	= new SyntaxHighlighter.Highlighter();
SyntaxHighlighter.brushes.Sql.aliases	= ['sql'];

The code below is a pasting of all the functions, keywords, and operators from the brush file, as well as some sample comments, to demonstrate the SyntaxHighlighter at work.

--One line comment
No Comment
/*Multi-line Comment
continued...*/
No Comment
/**************start big comment******************
big comment continued...
big comment continued...
/**************end big comment******************/
No Comment
/*
*Comment
*Comment
*Comment
*/

Functions:
abs acos app_name ascii asin assemblyproperty asymkey_id
asymkeyproperty atan atn2 avg case cast convert ceiling cert_id char
charindex checksum_agg coalesce col_length col_name collationproperty
columnproperty columns_updated containstable cos cot count count_big
current_timestamp current_user
database_principal_id databaseproperty databasepropertyex datalength
dateadd datediff datename datepart day db_id db_name degrees dense_rank
difference error_line error_message error_number error_procedure
error_severity error_state exp file_id file_idex file_name filegroup_id
filegroup_name filegroupproperty fileproperty floor fn_helpcollations
fn_listextendedproperty fn_my_permissions
fn_virtualfilestats formatmessage freetexttable fulltextcatalogproperty
fulltextserviceproperty getansinull getdate getutcdate grouping
has_perms_by_name host_id host_name ident_current ident_incr ident_seed
identity index_col indexkey_property indexproperty is_member
is_srvrolemember isdate isnull isnumeric key_guid key_id key_name
left len log log10 lower ltrim max min month nchar newid ntile nullif
object_definition object_id object_name object_schema_name
objectproperty objectpropertyex opendatasource openquery openrowset
openxml original_login parsename patindex pi
power pwdcompare pwdencrypt quotename radians rand rank replace
replicate reverse right round row_number rowcount_big rtrim
schema_id schema_name scope_identity serverproperty
session_user sessionproperty setuser sign sin soundex space
sql_variant_property sqrt square stats_date stdev stdevp str stuff
substring sum suser_id suser_name suser_sid suser_sname symkeyproperty
fn_builtin_permissions sysdatetime sysdatetimeoffset
system_user sysutcdatetime tan textptr textvalid type_id type_name
typeproperty unicode upper user_id user_name user_name var varp
xact_state year

Keywords:
add alter as asc authorization backup begin
break browse bulk by cascade check checkpoint
close clustered collate column commit compute
constraint contains continue create
current current_date current_time
cursor database dbcc deallocate declare default delete deny
desc disk distinct distributed double drop dump else end
errlvl escape except exec execute exit external fetch
file fillfactor for foreign freetext from full
function goto grant group having holdlock
identity_insert identitycol if index insert intersect
into is key kill lineno load merge national
nocheck nonclustered of off offsets on open
option order
over percent pivot plan precision primary print proc
procedure public raiserror read readtext reconfigure references
replication restore restrict return revert revoke rollback
rowcount rowguidcol rule save schema securityaudit select
set shutdown statistics
table tablesample textsize then to top tran transaction trigger
truncate tsequal union unique unpivot update updatetext use
user values varying view waitfor when where while with
bigint bit decimal int money numeric smallint smallmoney tinyint
float real date datetimeoffset datetime2 smalldatetime datetime time
binary image varbinary hierarchyid sql_variant timestamp uniqueidentifier xml

Operators:
all and any between exists cross in inner join like not null or outer some