<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
  <channel>
    <title>CodeKeep SQL Feed</title>
    <description>The latest and greatest SQL code snippets publicly available</description>
    <link>http://www.codekeep.net/feeds.aspx</link>
    <lastBuildDate>Wed, 23 May 2012 15:14:16 GMT</lastBuildDate>
    <docs>http://backend.userland.com/rss</docs>
    <generator>RSS.NET: http://www.rssdotnet.com/</generator>
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/CodeKeepSQL" /><feedburner:info uri="codekeepsql" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
      <title>Log Parser - Query IIS logs from multiple machines </title>
      <description>Description: Log Parser - Query IIS logs from multiple machines &lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/5c728b89-367c-40e9-9350-652281e41263.aspx'&gt;http://www.codekeep.net/snippets/5c728b89-367c-40e9-9350-652281e41263.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;SELECT * FROM \\machine1\c$\inetpub\logs\LogFiles\W3SVC1\u_ex*.log, \\machine1\c$\inetpub\logs\LogFiles\W3SVC1\u_*.log
WHERE s-port = 80&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/hPLHPsEwioA" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/hPLHPsEwioA/5c728b89-367c-40e9-9350-652281e41263.aspx</link>
      <pubDate>Wed, 23 May 2012 15:14:16 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/5c728b89-367c-40e9-9350-652281e41263.aspx</feedburner:origLink></item>
    <item>
      <title>Query Sproc contents</title>
      <description>Description: Query Sproc contents&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/b1b31f29-f70c-4615-a977-d7ab7947942f.aspx'&gt;http://www.codekeep.net/snippets/b1b31f29-f70c-4615-a977-d7ab7947942f.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;select SPECIFIC_SCHEMA, SPECIFIC_NAME, ROUTINE_DEFINITION from information_schema.routines
where routine_type='PROCEDURE'
--and SPECIFIC_SCHEMA like 'cms%' 
and ROUTINE_DEFINITION like '%meta%'
order by SPECIFIC_SCHEMA
&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/bk9EI9gz4I4" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/bk9EI9gz4I4/b1b31f29-f70c-4615-a977-d7ab7947942f.aspx</link>
      <pubDate>Tue, 08 May 2012 13:33:38 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/b1b31f29-f70c-4615-a977-d7ab7947942f.aspx</feedburner:origLink></item>
    <item>
      <title>Find all sql server running processes</title>
      <description>Description: Find all sql server running processes and transations&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/474e8e98-0fcc-4d55-9360-2ed150ad4148.aspx'&gt;http://www.codekeep.net/snippets/474e8e98-0fcc-4d55-9360-2ed150ad4148.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;sp_who2 

Select Distinct object_name(l.rsc_objid), l.req_spid, p.loginame
from master.dbo.syslockinfo l (nolock) join
master.dbo.sysprocesses p (nolock) on l.req_spid=p.spid
where object_name(l.rsc_objid) is not null

kill @spid&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/1sqvelocpfs" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/1sqvelocpfs/474e8e98-0fcc-4d55-9360-2ed150ad4148.aspx</link>
      <pubDate>Mon, 07 May 2012 14:56:40 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/474e8e98-0fcc-4d55-9360-2ed150ad4148.aspx</feedburner:origLink></item>
    <item>
      <title>Check and reclaim disk space</title>
      <description>Description: check free space and recycle errorlog to claim space back&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/749fce14-0310-4dfc-8e44-40bf222b3747.aspx'&gt;http://www.codekeep.net/snippets/749fce14-0310-4dfc-8e44-40bf222b3747.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;-- check free space
EXEC master..xp_fixeddrives
--drive MB free
------- -----------
--C 0 &amp;lt;------------- HELP !!!!!
--F 115360
--G 253473 
-- lets recycle the SQL Errorlog a few times to claim some space back
EXEC sp_cycle_errorlog WAITFOR DELAY '00:00:02'
GO
EXEC sp_cycle_errorlog WAITFOR DELAY '00:00:02'
GO
EXEC sp_cycle_errorlog WAITFOR DELAY '00:00:02'
GO
EXEC sp_cycle_errorlog WAITFOR DELAY '00:00:02'
GO
EXEC sp_cycle_errorlog WAITFOR DELAY '00:00:02'
GO
EXEC sp_cycle_errorlog WAITFOR DELAY '00:00:02'
GO
EXEC sp_cycle_errorlog
GO

-- check free space again
EXEC master..xp_fixeddrives
--drive MB free
------- -----------
--C 2500
--F 115360
--G 253477              
&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/-_dU5SAcJf4" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/-_dU5SAcJf4/749fce14-0310-4dfc-8e44-40bf222b3747.aspx</link>
      <pubDate>Wed, 28 Mar 2012 14:26:38 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/749fce14-0310-4dfc-8e44-40bf222b3747.aspx</feedburner:origLink></item>
    <item>
      <title>Tablespace.sql</title>
      <description>Description: Show Size, Space Used, Unused Space, Type, and Name of all database files&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/72c83002-abca-4890-942c-c7bf0377013a.aspx'&gt;http://www.codekeep.net/snippets/72c83002-abca-4890-942c-c7bf0377013a.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;set nocount on


print 'Show Size, Space Used, Unused Space, Type, and Name of all database files'

select
	[FileSizeMB]	=
		convert(numeric(10,2),sum(round(a.size/128.,2))),
        [UsedSpaceMB]	=
		convert(numeric(10,2),sum(round(fileproperty( a.name,'SpaceUsed')/128.,2))) ,
        [UnusedSpaceMB]	=
		convert(numeric(10,2),sum(round((a.size-fileproperty( a.name,'SpaceUsed'))/128.,2))) ,
	[Type] =
		case when a.groupid is null then '' when a.groupid = 0 then 'Log' else 'Data' end,
	[DBFileName]	= isnull(a.name,'*** Total for all files ***')
from
	sysfiles a
group by
	groupid,
	a.name
	with rollup
having
	a.groupid is null or
	a.name is not null
order by
	case when a.groupid is null then 99 when a.groupid = 0 then 0 else 1 end,
	a.groupid,
	case when a.name is null then 99 else 0 end,
	a.name




create table #TABLE_SPACE_WORK
(
	TABLE_NAME 	sysname		not null ,
	TABLE_ROWS 	numeric(18,0)	not null ,
	RESERVED 	varchar(50) 	not null ,
	DATA 		varchar(50) 	not null ,
	INDEX_SIZE 	varchar(50) 	not null ,
	UNUSED 		varchar(50) 	not null ,
)

create table #TABLE_SPACE_USED
(
	Seq		int		not null	
	identity(1,1)	primary key clustered,
	TABLE_NAME 	sysname		not null ,
	TABLE_ROWS 	numeric(18,0)	not null ,
	RESERVED 	varchar(50) 	not null ,
	DATA 		varchar(50) 	not null ,
	INDEX_SIZE 	varchar(50) 	not null ,
	UNUSED 		varchar(50) 	not null ,
)

create table #TABLE_SPACE
(
	Seq		int		not null
	identity(1,1)	primary key clustered,
	TABLE_NAME 	SYSNAME 	not null ,
	TABLE_ROWS 	int	 	not null ,
	RESERVED 	int	 	not null ,
	DATA 		int	 	not null ,
	INDEX_SIZE 	int	 	not null ,
	UNUSED 		int	 	not null ,
	USED_MB				numeric(18,4)	not null,
	USED_GB				numeric(18,4)	not null,
	AVERAGE_BYTES_PER_ROW		numeric(18,5)	null,
	AVERAGE_DATA_BYTES_PER_ROW	numeric(18,5)	null,
	AVERAGE_INDEX_BYTES_PER_ROW	numeric(18,5)	null,
	AVERAGE_UNUSED_BYTES_PER_ROW	numeric(18,5)	null,
)

declare @fetch_status int

declare @proc 	varchar(200)
select	@proc	= rtrim(db_name())+'.dbo.sp_spaceused'

declare Cur_Cursor cursor local
for
select
	TABLE_NAME	= 
	rtrim(TABLE_SCHEMA)+'.'+rtrim(TABLE_NAME)
from
	INFORMATION_SCHEMA.TABLES 
where
	TABLE_TYPE	= 'BASE TABLE'
order by
	1

open Cur_Cursor

declare @TABLE_NAME 	varchar(200)

select @fetch_status = 0

while @fetch_status = 0
	begin

	fetch next from Cur_Cursor
	into
		@TABLE_NAME

	select @fetch_status = @@fetch_status

	if @fetch_status &amp;lt;&amp;gt; 0
		begin
		continue
		end

	truncate table #TABLE_SPACE_WORK

	insert into #TABLE_SPACE_WORK
		(
		TABLE_NAME,
		TABLE_ROWS,
		RESERVED,
		DATA,
		INDEX_SIZE,
		UNUSED
		)
	exec @proc @objname = 
		@TABLE_NAME ,@updateusage = 'true'


	-- Needed to work with SQL 7
	update #TABLE_SPACE_WORK
	set
		TABLE_NAME = @TABLE_NAME

	insert into #TABLE_SPACE_USED
		(
		TABLE_NAME,
		TABLE_ROWS,
		RESERVED,
		DATA,
		INDEX_SIZE,
		UNUSED
		)
	select
		TABLE_NAME,
		TABLE_ROWS,
		RESERVED,
		DATA,
		INDEX_SIZE,
		UNUSED
	from
		#TABLE_SPACE_WORK

	end 	--While end

close Cur_Cursor

deallocate Cur_Cursor

insert into #TABLE_SPACE
	(
	TABLE_NAME,
	TABLE_ROWS,
	RESERVED,
	DATA,
	INDEX_SIZE,
	UNUSED,
	USED_MB,
	USED_GB,
	AVERAGE_BYTES_PER_ROW,
	AVERAGE_DATA_BYTES_PER_ROW,
	AVERAGE_INDEX_BYTES_PER_ROW,
	AVERAGE_UNUSED_BYTES_PER_ROW

	)
select
	TABLE_NAME,
	TABLE_ROWS,
	RESERVED,
	DATA,
	INDEX_SIZE,
	UNUSED,
	USED_MB			=
		round(convert(numeric(25,10),RESERVED)/
		convert(numeric(25,10),1024),4),
	USED_GB			=
		round(convert(numeric(25,10),RESERVED)/
		convert(numeric(25,10),1024*1024),4),
	AVERAGE_BYTES_PER_ROW	=
		case
		when TABLE_ROWS &amp;lt;&amp;gt; 0
		then round(
		(1024.000000*convert(numeric(25,10),RESERVED))/
		convert(numeric(25,10),TABLE_ROWS),5)
		else null
		end,
	AVERAGE_DATA_BYTES_PER_ROW	=
		case
		when TABLE_ROWS &amp;lt;&amp;gt; 0
		then round(
		(1024.000000*convert(numeric(25,10),DATA))/
		convert(numeric(25,10),TABLE_ROWS),5)
		else null
		end,
	AVERAGE_INDEX_BYTES_PER_ROW	=
		case
		when TABLE_ROWS &amp;lt;&amp;gt; 0
		then round(
		(1024.000000*convert(numeric(25,10),INDEX_SIZE))/
		convert(numeric(25,10),TABLE_ROWS),5)
		else null
		end,
	AVERAGE_UNUSED_BYTES_PER_ROW	=
		case
		when TABLE_ROWS &amp;lt;&amp;gt; 0
		then round(
		(1024.000000*convert(numeric(25,10),UNUSED))/
		convert(numeric(25,10),TABLE_ROWS),5)
		else null
		end
from
	(
	select
		TABLE_NAME,
		TABLE_ROWS,
		RESERVED	= 
		convert(int,rtrim(replace(RESERVED,'KB',''))),
		DATA		= 
		convert(int,rtrim(replace(DATA,'KB',''))),
		INDEX_SIZE	= 
		convert(int,rtrim(replace(INDEX_SIZE,'KB',''))),
		UNUSED		= 
		convert(int,rtrim(replace(UNUSED,'KB','')))
	from
		#TABLE_SPACE_USED aa
	) a
order by
	TABLE_NAME

print 'Show results in descending order by size in MB'

select * from #TABLE_SPACE order by USED_MB desc
go

drop table #TABLE_SPACE_WORK
drop table #TABLE_SPACE_USED 
drop table #TABLE_SPACE
&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/1BjNKGLWbIU" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/1BjNKGLWbIU/72c83002-abca-4890-942c-c7bf0377013a.aspx</link>
      <pubDate>Wed, 28 Mar 2012 14:23:59 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/72c83002-abca-4890-942c-c7bf0377013a.aspx</feedburner:origLink></item>
    <item>
      <title>Parse a list of integers usf_ParseIntegerArray</title>
      <description>Description: Takes a comma delimited list of integers as its input, returns a table listing those integers in a single column.&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/ea182584-42d0-45e4-b91c-210a3712c5b0.aspx'&gt;http://www.codekeep.net/snippets/ea182584-42d0-45e4-b91c-210a3712c5b0.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;CREATE FUNCTION dbo.usf_ParseIntegerArray 
(
@IntArray VARCHAR(MAX)
)
RETURNS 
@c TABLE (Col INT NOT NULL PRIMARY KEY)

AS
BEGIN

--remove whitespace
SET @IntArray = ','+@IntArray+','
SET @IntArray = REPLACE(@IntArray,CHAR(13),'')
SET @IntArray = REPLACE(@IntArray,CHAR(10),'')
SET @IntArray = REPLACE(@IntArray,CHAR(9) ,'')
SET @IntArray = REPLACE(@IntArray,CHAR(9) ,'')
SET @IntArray = REPLACE(@IntArray,   ' '  ,'')




DECLARE
	  @x INT
	, @e INT
	, @int INT
	, @CurrentCommaPos INT
	, @NextCommaPos INT
	, @intLength INT
	
SET @x = 1	
SET @e = dbo.usf_CountChar(@IntArray,',') - 1
SET @CurrentCommaPos = 1
SET @NextCommaPos = 2


WHILE @x &amp;lt;= @e
	BEGIN
		
		SET @NextCommaPos = CHARINDEX(',',@IntArray,@CurrentCommaPos+1)
		
		SET @intLength = @NextCommaPos - (@CurrentCommaPos+1)
		SET @int =
					CAST
					(
					SUBSTRING
						(
						 @IntArray
						,@CurrentCommaPos+1
						,@intLength
						)
					AS INT
					)
		IF @int NOT IN (SELECT Col FROM @c) AND @int IS NOT NULL INSERT INTO @c VALUES (@int)
		
		SET @CurrentCommaPos = @NextCommaPos
		
	SET @x = @x + 1
	END

RETURN 
END
;
GO&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/rUAV9lcQ09E" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/rUAV9lcQ09E/ea182584-42d0-45e4-b91c-210a3712c5b0.aspx</link>
      <pubDate>Thu, 26 Jan 2012 22:35:03 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/ea182584-42d0-45e4-b91c-210a3712c5b0.aspx</feedburner:origLink></item>
    <item>
      <title>Hints for moving tables between SQL Schemas</title>
      <description>Description: How to move tables between different schemas within SQL Server&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/3deab9ab-e6f7-4528-949b-b2fe91babbf4.aspx'&gt;http://www.codekeep.net/snippets/3deab9ab-e6f7-4528-949b-b2fe91babbf4.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;ALTER SCHEMA bnk TRANSFER dbo.test
              ^              ^
              |              |
           to schema      from schema

List alter statements

SELECT 'ALTER SCHEMA newSchema TRANSFER ' + TABLE_SCHEMA + '.' + TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo'


&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/AkMRgxPq4Mg" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/AkMRgxPq4Mg/3deab9ab-e6f7-4528-949b-b2fe91babbf4.aspx</link>
      <pubDate>Wed, 25 Jan 2012 14:06:51 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/3deab9ab-e6f7-4528-949b-b2fe91babbf4.aspx</feedburner:origLink></item>
    <item>
      <title>recover db from suspect state</title>
      <description>Description: recover db from suspect state&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/d98d1fbc-5bfd-43fd-9bb2-3a482b7af278.aspx'&gt;http://www.codekeep.net/snippets/d98d1fbc-5bfd-43fd-9bb2-3a482b7af278.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;EXEC sp_resetstatus 'dbname';
ALTER DATABASE dbname SET EMERGENCY
DBCC checkdb('dbname')
ALTER DATABASE dbname SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DBCC CheckDB ('dbname', REPAIR_ALLOW_DATA_LOSS)
ALTER DATABASE dbname SET MULTI_USER&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/mLTcJ9e3q2w" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/mLTcJ9e3q2w/d98d1fbc-5bfd-43fd-9bb2-3a482b7af278.aspx</link>
      <pubDate>Fri, 16 Dec 2011 09:34:11 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/d98d1fbc-5bfd-43fd-9bb2-3a482b7af278.aspx</feedburner:origLink></item>
    <item>
      <title>convert ((int)year,(int)month,(int)day) to Datetime</title>
      <description>Description: convert ((int)year,(int)month,(int)day) to Datetime&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/ccc0d9a6-0d18-4f2d-adbf-266027bc254c.aspx'&gt;http://www.codekeep.net/snippets/ccc0d9a6-0d18-4f2d-adbf-266027bc254c.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;SELECT
   CAST(
      CAST(year AS VARCHAR(4)) +
      RIGHT('0' + CAST(month AS VARCHAR(2)), 2) +
      RIGHT('0' + CAST(day AS VARCHAR(2)), 2) 
   AS DATETIME)&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/0s1RIT4zfqg" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/0s1RIT4zfqg/ccc0d9a6-0d18-4f2d-adbf-266027bc254c.aspx</link>
      <pubDate>Thu, 01 Dec 2011 16:09:35 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/ccc0d9a6-0d18-4f2d-adbf-266027bc254c.aspx</feedburner:origLink></item>
    <item>
      <title>Creating Random SQL Server Test Data </title>
      <description>Description: http://www.mitchelsellers.com/blogs/articletype/articleview/articleid/249/creating-random-sql-server-test-data.aspx&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/7189e2d4-6e9b-4a78-9a5a-0754fbcf4689.aspx'&gt;http://www.codekeep.net/snippets/7189e2d4-6e9b-4a78-9a5a-0754fbcf4689.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;CREATE TABLE dbo.TestTableSize
(
	MyKeyField VARCHAR(10) NOT NULL,
	MyDate1 DATETIME NOT NULL,
	MyDate2 DATETIME NOT NULL,
	MyDate3 DATETIME NOT NULL,
	MyDate4 DATETIME NOT NULL,
	MyDate5 DATETIME NOT NULL
)

DECLARE @RowCount INT
DECLARE @RowString VARCHAR(10)
DECLARE @Random INT
DECLARE @Upper INT
DECLARE @Lower INT
DECLARE @InsertDate DATETIME

SET @Lower = -730
SET @Upper = -1
SET @RowCount = 0

WHILE @RowCount &amp;lt; 3000000
BEGIN
	SET @RowString = CAST(@RowCount AS VARCHAR(10))
	SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
	SET @InsertDate = DATEADD(dd, @Random, GETDATE())
	
	INSERT INTO TestTableSize
		(MyKeyField
		,MyDate1
		,MyDate2
		,MyDate3
		,MyDate4
		,MyDate5)
	VALUES
		(REPLICATE('0', 10 - DATALENGTH(@RowString)) + @RowString
		, @InsertDate
		,DATEADD(dd, 1, @InsertDate)
		,DATEADD(dd, 2, @InsertDate)
		,DATEADD(dd, 3, @InsertDate)
		,DATEADD(dd, 4, @InsertDate))

	SET @RowCount = @RowCount + 1
END&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/cEZG_q2ljh8" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/cEZG_q2ljh8/7189e2d4-6e9b-4a78-9a5a-0754fbcf4689.aspx</link>
      <pubDate>Thu, 17 Nov 2011 11:11:59 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/7189e2d4-6e9b-4a78-9a5a-0754fbcf4689.aspx</feedburner:origLink></item>
    <item>
      <title>SQL Collate Multiple Rows Into One</title>
      <description>Description: SQL Collate and combine multiple rows into single row with comma between rows.&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/a54c07cd-5eb5-4bf6-a43e-306c245c946a.aspx'&gt;http://www.codekeep.net/snippets/a54c07cd-5eb5-4bf6-a43e-306c245c946a.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;DECLARE @List VARCHAR(8000)  
SELECT @List = COALESCE(@List + ', ', '') + (ServiceCode)
FROM  Services
WHERE ServiceID &amp;lt; 10 

PRINT @List

----------------- ALT METHOD ----------------

SELECT 
ROW_NUMBER() OVER(ORDER BY C.CaseID) AS ID,
CaseID,
		REPLACE(REPLACE((SELECT SVC.ServiceCode	 
			FROM  Services SVC (NOLOCK)
				INNER JOIN dbo.CaseServices CS
					ON SVC.ServiceID = CS.ServiceID
				WHERE CS.CaseID = C.CaseID
			FOR XML PATH('')),'&amp;lt;ServiceCode&amp;gt;',''),'&amp;lt;/ServiceCode&amp;gt;',',')
	FROM Cases C (NOLOCK) 
	WHERE OrderID = 36911&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/Zvhoo92SKgY" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/Zvhoo92SKgY/a54c07cd-5eb5-4bf6-a43e-306c245c946a.aspx</link>
      <pubDate>Thu, 27 Oct 2011 18:23:53 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/a54c07cd-5eb5-4bf6-a43e-306c245c946a.aspx</feedburner:origLink></item>
    <item>
      <title>SQL Temp Table Variable</title>
      <description>Description: SQL Temp Table Variable. Example shows how to insert list of database names into a temp table.&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/3f4da5ab-7b44-4a1a-adaf-8f75af3cbd3e.aspx'&gt;http://www.codekeep.net/snippets/3f4da5ab-7b44-4a1a-adaf-8f75af3cbd3e.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;DECLARE @TVar TABLE (DBName VARCHAR(50) NOT NULL)

INSERT INTO @TVar (DBName) 
SELECT dbo.sysdatabases.name AS DBname
FROM dbo.sysaltfiles INNER JOIN dbo.sysdatabases ON 
            dbo.sysaltfiles.dbid = dbo.sysdatabases.dbid 
WHERE dbo.sysdatabases.name 
            NOT IN ( 
					'Northwind', 
					'pubs', 
					'tempdb', 
					'master', 
					'model', 
					'msdb',
					'ReportServerTempDB',
					'GTTemp',
					'RMinder'
					)
	AND dbo.sysaltfiles.name NOT LIKE '%log'
	AND dbo.sysaltfiles.name NOT LIKE '%Restore'&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/gu02tFozziE" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/gu02tFozziE/3f4da5ab-7b44-4a1a-adaf-8f75af3cbd3e.aspx</link>
      <pubDate>Thu, 27 Oct 2011 15:54:42 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/3f4da5ab-7b44-4a1a-adaf-8f75af3cbd3e.aspx</feedburner:origLink></item>
    <item>
      <title>SQL Date Only</title>
      <description>Description: SQL DateOnly, StartofWeek, EndOfWeek. Removes time from the Date object.&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/34ab2dab-db10-482e-a4d0-0252329ce13f.aspx'&gt;http://www.codekeep.net/snippets/34ab2dab-db10-482e-a4d0-0252329ce13f.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;-- Date Only (Strips time)
SELECT DATEADD(day, DATEDIFF(day, 0, CURRENT_TIMESTAMP), 0) AS DATEONLY

-- First Date in the week
SELECT DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6) AS START_OF_WEEK 

-- Last Date in the week
SELECT DATEADD(wk, DATEDIFF(wk, 6, CURRENT_TIMESTAMP), 6 + 6) AS END_OF_WEEK &lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/RxNyJ2GZ5NI" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/RxNyJ2GZ5NI/34ab2dab-db10-482e-a4d0-0252329ce13f.aspx</link>
      <pubDate>Wed, 26 Oct 2011 19:06:53 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/34ab2dab-db10-482e-a4d0-0252329ce13f.aspx</feedburner:origLink></item>
    <item>
      <title>SQL Restore</title>
      <description>Description: SQL Restore&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/42a7e663-f844-45bd-ad62-11fc9e1973aa.aspx'&gt;http://www.codekeep.net/snippets/42a7e663-f844-45bd-ad62-11fc9e1973aa.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;RESTORE DATABASE [MydbName] FROM  DISK = N'D:\Restores\MydbName.bak' WITH  FILE = 1,  MOVE N'MydbName' TO N'D:\Database\MSSQL.1\MSSQL\Data\MydbName.mdf',  MOVE N'MydbName_log' TO N'D:\Database\MSSQL.1\MSSQL\Data\MydbName.ldf',  NOUNLOAD,  REPLACE,  STATS = 10
GO
&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/7TtQ9ppmREI" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/7TtQ9ppmREI/42a7e663-f844-45bd-ad62-11fc9e1973aa.aspx</link>
      <pubDate>Mon, 17 Oct 2011 17:30:47 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/42a7e663-f844-45bd-ad62-11fc9e1973aa.aspx</feedburner:origLink></item>
    <item>
      <title>SQL Email Set up</title>
      <description>Description: This enables email on the SQL Server.&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/5c1f6265-dc74-443b-90ab-3a355a9afe80.aspx'&gt;http://www.codekeep.net/snippets/5c1f6265-dc74-443b-90ab-3a355a9afe80.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;sp_configure 'show advanced options' , 1
GO

RECONFIGURE WITH OVERRIDE;
GO

EXEC sp_configure 'Database Mail XPs', 1
GO

RECONFIGURE WITH OVERRIDE;
GO

-- Next expand the Management Node
-- Right click over DATABASE MAIL
-- Select CONFIGURE DATABSE MAIL
-- In last step of Wizard be sure to check PUBLIC and set a DEFAULT to YES.&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/zjgds0xx2M4" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/zjgds0xx2M4/5c1f6265-dc74-443b-90ab-3a355a9afe80.aspx</link>
      <pubDate>Mon, 17 Oct 2011 14:09:37 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/5c1f6265-dc74-443b-90ab-3a355a9afe80.aspx</feedburner:origLink></item>
    <item>
      <title>sqlplus alter session for date</title>
      <description>Description: Alter session to set date format in sql plus.&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/472e9886-aa1b-4f19-861b-22f6a1a6a0eb.aspx'&gt;http://www.codekeep.net/snippets/472e9886-aa1b-4f19-861b-22f6a1a6a0eb.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY MM DD';
select sysdate from dual;&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/PQp33RjKnaA" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/PQp33RjKnaA/472e9886-aa1b-4f19-861b-22f6a1a6a0eb.aspx</link>
      <pubDate>Fri, 14 Oct 2011 23:51:26 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/472e9886-aa1b-4f19-861b-22f6a1a6a0eb.aspx</feedburner:origLink></item>
    <item>
      <title>What SQL Statements Are Currently Executing Utility</title>
      <description>Description: more info
http://www.sqlservercentral.com/articles/dmv/64425/&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/0a4730e0-19f7-4d09-bb73-7b351851a397.aspx'&gt;http://www.codekeep.net/snippets/0a4730e0-19f7-4d09-bb73-7b351851a397.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt; -- Do not lock anything, and do not get held up by any locks.
    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

    -- What SQL Statements Are Currently Running?
    SELECT [Spid] = session_Id
	, ecid
	, [Database] = DB_NAME(sp.dbid)
	, [User] = nt_username
	, [Status] = er.status
	, [Wait] = wait_type
	, [Individual Query] = SUBSTRING (qt.text, 
             er.statement_start_offset/2,
	(CASE WHEN er.statement_end_offset = -1
	       THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
		ELSE er.statement_end_offset END - 
                                er.statement_start_offset)/2)
	,[Parent Query] = qt.text
	, Program = program_name
	, Hostname
	, nt_domain
	, start_time
    FROM sys.dm_exec_requests er
    INNER JOIN sys.sysprocesses sp ON er.session_id = sp.spid
    CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
    WHERE session_Id &amp;gt; 50              -- Ignore system spids.
    AND session_Id NOT IN (@@SPID)     -- Ignore this current statement.
    ORDER BY 1, 2&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/u-6Lhv8yHqg" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/u-6Lhv8yHqg/0a4730e0-19f7-4d09-bb73-7b351851a397.aspx</link>
      <pubDate>Mon, 10 Oct 2011 11:03:52 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/0a4730e0-19f7-4d09-bb73-7b351851a397.aspx</feedburner:origLink></item>
    <item>
      <title>COPY DATA FROM TABLE TO TABLE</title>
      <description>Description: COPY DATA FROM TABLE TO TABLE&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/69774736-33e8-4023-ab73-2f80e664158f.aspx'&gt;http://www.codekeep.net/snippets/69774736-33e8-4023-ab73-2f80e664158f.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;USE [master]
GO
/****** Object:  StoredProcedure [dbo].[COPY_TABLE]    Script Date: 10/17/2011 11:44:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/***
OBJET :		STORED PROCEDURE
AUTHOR :		ELAMEEN ELSAYED
DESC :		MOVE TABLE'S ENTIRE DATA TO ANOTHER TABLE
VERSION 2011/10/08 :		@PRINT VARIABLE TO PRINT QUERY,
@BASE VARIABLE TO SPECIFY FROM WHICH TABLE THE LIST OF COLUMNS ARE GOING TO BE ACQUIRED
VERSION 2011/10/16 :		CHECK IF THE TABLE HAS IDENTITY FIRST,
@APPEND VARIABLE TO APPEND ROWS


***/
ALTER PROC [dbo].[COPY_TABLE] (
@SRC_DB NVARCHAR(100),
@SRC_SCHMA NVARCHAR(100),
@SRC_TBL NVARCHAR(100),

@DSTN_DB NVARCHAR(100),
@DSTN_SCHMA NVARCHAR(100),
@DSTN_TBL NVARCHAR(100),
@PRINT BIT=1,
@BASE BIT=0,
@APPEND BIT=0
)
AS
BEGIN
		
		DECLARE @LQS NVARCHAR(MAX), @LQS2 NVARCHAR(MAX),@COLS_TABLE NVARCHAR(MAX),@DB_COLS_TABLE NVARCHAR(MAX)
		IF @BASE=1 
			SELECT @DB_COLS_TABLE=@DSTN_DB,@COLS_TABLE=@DSTN_TBL 
		ELSE
			SELECT @DB_COLS_TABLE=@SRC_DB,@COLS_TABLE=@SRC_TBL 
			
		SELECT @LQS='
		DECLARE @COLS_LST NVARCHAR(MAX),@CMD NVARCHAR(MAX) 
		SELECT @COLS_LST=STUFF((SELECT  '',''+COLUMN_NAME
		FROM   '+@DB_COLS_TABLE+'.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='''+@COLS_TABLE+'''
		FOR XML PATH('''')),1,1,'''');'+
		CASE WHEN @APPEND=0 THEN  +' DELETE FROM  '+@DSTN_DB+'.'+@DSTN_SCHMA+'.'+@DSTN_TBL+';' ELSE '' END +
		' SELECT @CMD=''SET IDENTITY_INSERT  '+@DSTN_DB+'.'+@DSTN_SCHMA+'.'+@DSTN_TBL+' ON;INSERT INTO '+@DSTN_DB+'.'+@DSTN_SCHMA+'.'+@DSTN_TBL+' (''+@COLS_LST+'')
		SELECT ''+@COLS_LST+'' FROM '+@SRC_DB+'.'+@SRC_SCHMA+'.'+@SRC_TBL+';SET IDENTITY_INSERT  '+@DSTN_DB+'.'+@DSTN_SCHMA+'.'+@DSTN_TBL+' OFF;'';
		
		EXEC SP_EXECUTESQL @CMD;
		'
		--CHECK IF DOESN'T HAVE IDENTITY
		DECLARE @IDENT_FLG BIT;
		SELECT @LQS2 ='
		USE '+@DSTN_DB+';
		SELECT @IDENT_FLG=COALESCE(OBJECTPROPERTY(OBJECT_ID('''+@DSTN_TBL+''') , ''TableHasIdentity''),0);
		'
		EXEC SP_EXECUTESQL @LQS2,N'@IDENT_FLG BIT OUTPUT',@IDENT_FLG OUTPUT
					
					 
		IF @IDENT_FLG=0
			BEGIN
				--WITHOUT IDENTITY
				SELECT @LQS='
				DECLARE @COLS_LST NVARCHAR(MAX),@CMD NVARCHAR(MAX) 
				SELECT @COLS_LST=STUFF((SELECT  '',''+COLUMN_NAME
				FROM   '+@DB_COLS_TABLE+'.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='''+@COLS_TABLE+'''
				FOR XML PATH('''')),1,1,'''');'+
				CASE WHEN @APPEND=0 THEN  +' DELETE FROM  '+@DSTN_DB+'.'+@DSTN_SCHMA+'.'+@DSTN_TBL+';' ELSE '' END +
				'SELECT @CMD=''INSERT INTO '+@DSTN_DB+'.'+@DSTN_SCHMA+'.'+@DSTN_TBL+' (''+@COLS_LST+'')
				SELECT ''+@COLS_LST+'' FROM '+@SRC_DB+'.'+@SRC_SCHMA+'.'+@SRC_TBL+';'';
				
				EXEC SP_EXECUTESQL @CMD;
				'
			END
		IF @PRINT =1 
			PRINT  @LQS
		ELSE
			EXEC SP_EXECUTESQL @LQS
				
END


&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/6zicH4e8TL8" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/6zicH4e8TL8/69774736-33e8-4023-ab73-2f80e664158f.aspx</link>
      <pubDate>Wed, 05 Oct 2011 06:31:45 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/69774736-33e8-4023-ab73-2f80e664158f.aspx</feedburner:origLink></item>
    <item>
      <title>READ EXCELL</title>
      <description>Description: Read Excell file into Sql Server&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/ab729219-61f0-4c4a-8573-bd69dde9c0f9.aspx'&gt;http://www.codekeep.net/snippets/ab729219-61f0-4c4a-8573-bd69dde9c0f9.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;EXECUTE sp_configure 'show advanced options', 1
RECONFIGURE WITH OVERRIDE
GO

EXECUTE sp_configure 'Ad Hoc Distributed Queries', '1'
RECONFIGURE WITH OVERRIDE
GO

EXECUTE sp_configure 'show advanced options', 0
RECONFIGURE WITH OVERRIDE
GO
--insert into tbAll
SELECT *
FROM
OPENROWSET
('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\Documents and Settings\administrator\Desktop\MRG1.xlsx;Extended Properties=Excel 12.0 XML;HDR=YES',
'SELECT * FROM [Sheet1$]')
--load 2008
 &lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/XEqfH416T1s" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/XEqfH416T1s/ab729219-61f0-4c4a-8573-bd69dde9c0f9.aspx</link>
      <pubDate>Wed, 05 Oct 2011 05:53:56 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/ab729219-61f0-4c4a-8573-bd69dde9c0f9.aspx</feedburner:origLink></item>
    <item>
      <title>DISPLAY HIERARCHY DATA</title>
      <description>Description: DISPLAY HIERARCHY DATA IN A RECURSIVE CHILD PARENT COLUMNS&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/b0b84cdf-6c54-40ba-a496-70be353ceee2.aspx'&gt;http://www.codekeep.net/snippets/b0b84cdf-6c54-40ba-a496-70be353ceee2.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;declare @t table (id int, parent int)
insert @t (id, parent) 
SELECT  EmployeeID,ReportsTo
FROM NORTHWIND..Employees
; with cte as (
    select  id, parent
    ,       cast(RIGHT(REPLICATE(' ',12) + 
                 CONVERT(varchar(12),id),12) as varchar(max)) Path
    from    @t
    where   parent is null
    union all
    select  child.id, child.parent
    ,       parent.Path + RIGHT(REPLICATE(' ',12) + 
                                CONVERT(varchar(12),child.id),12) as Path
    from    @t child
    join    cte parent
    on      parent.id = child.parent
)
select  *
from    cte
order by        Path&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/Cc5NDyWACMs" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/Cc5NDyWACMs/b0b84cdf-6c54-40ba-a496-70be353ceee2.aspx</link>
      <pubDate>Tue, 04 Oct 2011 06:42:18 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/b0b84cdf-6c54-40ba-a496-70be353ceee2.aspx</feedburner:origLink></item>
    <item>
      <title>ltrim rtrim UDF</title>
      <description>Description: trims out given characters from left or right side of a given string&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/89b7e2d8-4172-47d5-959e-db5950df3760.aspx'&gt;http://www.codekeep.net/snippets/89b7e2d8-4172-47d5-959e-db5950df3760.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;create function [dbo].[rtrim]
/*
    Author: Sergey Nefedyev
    Date: 2011-09-27

    UDF Fuction that returns passed in @string value after removing characters in 
    @remove from right side of the string

    Sample Call
        SELECT dbo.rtrim('ABCD987*', '*789A')
    Output
	   ABCD
*/
(
 @string nvarchar(max), 
 @remove nvarchar(100)
)
returns nvarchar(max)
as
begin
    while right(@string, 1) like '[' + @remove + ']'
    begin
        set @string = substring(@string, 1, datalength(@string)/2-1)
    end
    return @string
end
go

create function [dbo].[ltrim]
/*
    Author: Sergey Nefedyev
    Date: 2011-09-27

    UDF Fuction that returns passed in @string value after removing characters in 
    @remove from left side of the string

    Sample Call
        SELECT dbo.ltrim('ABCD987*', 'DCBA*')
    Output
	   987*
*/
(
 @string nvarchar(max), 
 @remove nvarchar(100)
)
returns nvarchar(max)
as
begin
    while left(@string, 1) like '[' + @remove + ']'
    begin
        set @string = substring(@string, 2, datalength(@string)/2-1)
    end
    return @string
end
go

create function [dbo].[trim]
/*
    Author: Sergey Nefedyev
    Date: 2011-09-27

    UDF Fuction that returns passed in @string value after removing characters in 
    @remove from left and right sides of the string

    Sample Call
        SELECT dbo.trim('ABCD987*', 'D9BA7*')
    Output
	   CD98
*/
(
 @string nvarchar(max), 
 @remove nvarchar(100)
)
returns nvarchar(max)
as
begin
    return dbo.ltrim(dbo.rtrim(@string, @remove), @remove)
end
go
&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/GpGRMc0v-Ek" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/GpGRMc0v-Ek/89b7e2d8-4172-47d5-959e-db5950df3760.aspx</link>
      <pubDate>Wed, 28 Sep 2011 16:26:17 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/89b7e2d8-4172-47d5-959e-db5950df3760.aspx</feedburner:origLink></item>
    <item>
      <title>Specific word or phrase from all stored procedure, views, and triggers </title>
      <description>Description: Find Specific word or phrase from all stored procedure, views, and triggers available in SQL Server 2005/2008&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/6a59c226-f6b1-477b-b40c-05911456c9f5.aspx'&gt;http://www.codekeep.net/snippets/6a59c226-f6b1-477b-b40c-05911456c9f5.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;SELECT DISTINCT so.name,sc.text
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE so.xtype in ('P','TR','V') and sc.TEXT LIKE '%fsu%'
order by name
&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/2fi206ax_hY" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/2fi206ax_hY/6a59c226-f6b1-477b-b40c-05911456c9f5.aspx</link>
      <pubDate>Thu, 22 Sep 2011 08:24:56 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/6a59c226-f6b1-477b-b40c-05911456c9f5.aspx</feedburner:origLink></item>
    <item>
      <title>Kill MSSQL DB connections</title>
      <description>Description: This script will kill all current connections to a database in MSSQL.  This is useful for detaching the database, restoring it or performing other tasks that require all connections dropped from the database.&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/78688de6-4801-42ad-abc3-fb7d28e2c3b2.aspx'&gt;http://www.codekeep.net/snippets/78688de6-4801-42ad-abc3-fb7d28e2c3b2.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;DECLARE @SQL VARCHAR(8000)

SELECT @SQL=COALESCE(@SQL,'')+'Kill '+CAST(spid AS VARCHAR(10))+ '; '
FROM sys.sysprocesses
WHERE DBID=DB_ID('&amp;lt;DATABASE_NAME&amp;gt;')

EXEC(@SQL)&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/lvPMzpvFce0" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/lvPMzpvFce0/78688de6-4801-42ad-abc3-fb7d28e2c3b2.aspx</link>
      <pubDate>Tue, 13 Sep 2011 21:07:31 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/78688de6-4801-42ad-abc3-fb7d28e2c3b2.aspx</feedburner:origLink></item>
    <item>
      <title>SQL Server UPSERT Example</title>
      <description>Description: A merge type statement for SQL Server prior to 2008&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/14b6d8ca-3796-48a5-8ba2-d67660f56374.aspx'&gt;http://www.codekeep.net/snippets/14b6d8ca-3796-48a5-8ba2-d67660f56374.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Stephen Smith
-- Create date: 24 August 2011
-- Description:	Saves or Updates a Saga state
-- =============================================
CREATE PROCEDURE SaveSaga 
	@id uniqueidentifier, 
	@name nvarchar(255),
	@state nvarchar(255),
	@xml text
AS
BEGIN
	BEGIN TRANSACTION Upsert
	
	update Saga with (serializable)
	set ID=@id, Name=@name, [State]=@state, [xml]=@xml, PersistedOn = GETDATE()
	where ID=@id
	
	if @@rowcount = 0
	
	insert into Saga (ID, Name, [State], [Xml], PersistedOn)
	values (@id, @name, @state, @xml, GETDATE()) 

	COMMIT TRANSACTION Upsert
END
GO&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/3kTaIzfsJEQ" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/3kTaIzfsJEQ/14b6d8ca-3796-48a5-8ba2-d67660f56374.aspx</link>
      <pubDate>Thu, 25 Aug 2011 13:09:35 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/14b6d8ca-3796-48a5-8ba2-d67660f56374.aspx</feedburner:origLink></item>
    <item>
      <title>Add Trigger to Table Last Update Date</title>
      <description>Description: Add a trigger to a table to update a date column with the current UTC Date Time value. This trigger will update all UPDATEs to the table.&lt;br /&gt;&lt;br /&gt;Link: &lt;a href='http://www.codekeep.net/snippets/dcc2724f-c438-4aee-89d9-799a0d49edc1.aspx'&gt;http://www.codekeep.net/snippets/dcc2724f-c438-4aee-89d9-799a0d49edc1.aspx&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre style='font-size: 9pt;'&gt;-- =============================================
-- Author: &amp;lt;Author,,Name&amp;gt;
-- Create date: &amp;lt;Create Date,,&amp;gt;
-- Description:	&amp;lt;Description,,&amp;gt;
-- =============================================
CREATE TRIGGER trgUpdateMYTABLE ON MYTABLE FOR UPDATE AS
BEGIN
	UPDATE MYTABLE
	SET LastModified = GETUTCDATE()
	FROM MYTABLE INNER JOIN deleted d
	ON Attachments.ID = d.ID
END
GO&lt;/pre&gt;&lt;img src="http://feeds.feedburner.com/~r/CodeKeepSQL/~4/YoCSC2J0p2g" height="1" width="1"/&gt;</description>
      <link>http://feedproxy.google.com/~r/CodeKeepSQL/~3/YoCSC2J0p2g/dcc2724f-c438-4aee-89d9-799a0d49edc1.aspx</link>
      <pubDate>Thu, 25 Aug 2011 06:03:05 GMT</pubDate>
    <feedburner:origLink>http://www.codekeep.net/snippets/dcc2724f-c438-4aee-89d9-799a0d49edc1.aspx</feedburner:origLink></item>
  </channel>
</rss>

