Wednesday, December 21, 2011

SQL SERVER – Find Row Count in Table – Find Largest Table in Database – T-SQL « SQL Server Journey with SQLAuthority

SQL SERVER – Find Row Count in Table – Find Largest Table in Database – T-SQL « SQL Server Journey with SQLAuthority

How do I get a list of SQL Server tables and their row counts?

How do I get a list of SQL Server tables and their row counts?

Monday, October 24, 2011

sp_helpindex3

CREATE procedure [dbo].[sp_helpindex3] @objname nvarchar(776) -- the table to check for indexes as -- PRELIM set nocount on declare @objid int, -- the object id of the table @indid smallint, -- the index id of an index @groupid int, -- the filegroup id of an index @indname sysname, @groupname sysname, @status int, @keys nvarchar(2126), --Length (16*max_identifierLength)+(15*2)+(16*3) @inc_columns nvarchar(max), @inc_Count smallint, @loop_inc_Count smallint, @dbname sysname, @ignore_dup_key bit, @is_unique bit, @is_hypothetical bit, @is_primary_key bit, @is_unique_key bit, @auto_created bit, @no_recompute bit, @filter_definition nvarchar(max) -- Check to see that the object names are local to the current database. select @dbname = parsename(@objname,3) if @dbname is null select @dbname = db_name() else if @dbname <> db_name() begin raiserror(15250,-1,-1) return (1) end -- Check to see the the table exists and initialize @objid. select @objid = object_id(@objname) if @objid is NULL begin raiserror(15009,-1,-1,@objname,@dbname) return (1) end -- OPEN CURSOR OVER INDEXES (skip stats: bug shiloh_51196) declare ms_crs_ind cursor local static for select i.index_id, i.data_space_id, i.name, i.ignore_dup_key, i.is_unique, i.is_hypothetical, i.is_primary_key, i.is_unique_constraint, s.auto_created, s.no_recompute, i.filter_definition from sys.indexes i join sys.stats s on i.object_id = s.object_id and i.index_id = s.stats_id where i.object_id = @objid open ms_crs_ind fetch ms_crs_ind into @indid, @groupid, @indname, @ignore_dup_key, @is_unique, @is_hypothetical, @is_primary_key, @is_unique_key, @auto_created, @no_recompute, @filter_definition -- IF NO INDEX, QUIT if @@fetch_status < 0 begin deallocate ms_crs_ind raiserror(15472,-1,-1,@objname) -- Object does not have any indexes. return (0) end -- create temp tables CREATE TABLE #spindtab ( index_name sysname collate database_default NOT NULL, index_id int, ignore_dup_key bit, is_unique bit, is_hypothetical bit, is_primary_key bit, is_unique_key bit, auto_created bit, no_recompute bit, groupname sysname collate database_default NULL, index_keys nvarchar(2126) collate database_default NOT NULL, -- see @keys above for length descr filter_definition nvarchar(max), inc_Count smallint, inc_columns nvarchar(max) ) CREATE TABLE #IncludedColumns ( RowNumber smallint, [Name] nvarchar(128) ) -- Now check out each index, figure out its type and keys and -- save the info in a temporary table that we'll print out at the end. while @@fetch_status >= 0 begin -- First we'll figure out what the keys are. declare @i int, @thiskey nvarchar(131) -- 128+3 select @keys = index_col(@objname, @indid, 1), @i = 2 if (indexkey_property(@objid, @indid, 1, 'isdescending') = 1) select @keys = @keys + '(-)' select @thiskey = index_col(@objname, @indid, @i) if ((@thiskey is not null) and (indexkey_property(@objid, @indid, @i, 'isdescending') = 1)) select @thiskey = @thiskey + '(-)' while (@thiskey is not null ) begin select @keys = @keys + ', ' + @thiskey, @i = @i + 1 select @thiskey = index_col(@objname, @indid, @i) if ((@thiskey is not null) and (indexkey_property(@objid, @indid, @i, 'isdescending') = 1)) select @thiskey = @thiskey + '(-)' end -- Second, we'll figure out what the included columns are. SELECT @inc_Count = count(*) FROM sys.tables AS tbl INNER JOIN sys.indexes AS si ON (si.index_id > 0 and si.is_hypothetical = 0) AND (si.object_id=tbl.object_id) INNER JOIN sys.index_columns AS ic ON (ic.column_id > 0 and (ic.key_ordinal > 0 or ic.partition_ordinal = 0 or ic.is_included_column != 0)) AND (ic.index_id=CAST(si.index_id AS int) AND ic.object_id=si.object_id) INNER JOIN sys.columns AS clmns ON clmns.object_id = ic.object_id and clmns.column_id = ic.column_id WHERE ic.is_included_column = 1 and (si.index_id = @indid) and (tbl.object_id= @objid) IF @inc_Count > 0 INSERT #IncludedColumns SELECT ROW_NUMBER() OVER (ORDER BY clmns.column_id) , clmns.name FROM sys.tables AS tbl INNER JOIN sys.indexes AS si ON (si.index_id > 0 and si.is_hypothetical = 0) AND (si.object_id=tbl.object_id) INNER JOIN sys.index_columns AS ic ON (ic.column_id > 0 and (ic.key_ordinal > 0 or ic.partition_ordinal = 0 or ic.is_included_column != 0)) AND (ic.index_id=CAST(si.index_id AS int) AND ic.object_id=si.object_id) INNER JOIN sys.columns AS clmns ON clmns.object_id = ic.object_id and clmns.column_id = ic.column_id WHERE ic.is_included_column = 1 and (si.index_id = @indid) and (tbl.object_id= @objid) SELECT @inc_columns = [Name] FROM #IncludedColumns WHERE RowNumber = 1 SET @loop_inc_Count = 1 WHILE @loop_inc_Count < @inc_Count BEGIN SELECT @inc_columns = @inc_columns + ', ' + [Name] FROM #IncludedColumns WHERE RowNumber = @loop_inc_Count + 1 SET @loop_inc_Count = @loop_inc_Count + 1 END select @groupname = null select @groupname = name from sys.data_spaces where data_space_id = @groupid -- INSERT ROW FOR INDEX insert into #spindtab values (@indname, @indid, @ignore_dup_key, @is_unique, @is_hypothetical, @is_primary_key, @is_unique_key, @auto_created, @no_recompute, @groupname, @keys, @filter_definition, @inc_Count, @inc_columns) -- Next index fetch ms_crs_ind into @indid, @groupid, @indname, @ignore_dup_key, @is_unique, @is_hypothetical, @is_primary_key, @is_unique_key, @auto_created, @no_recompute, @filter_definition end deallocate ms_crs_ind -- DISPLAY THE RESULTS select 'index_name' = index_name, 'index_description' = convert(varchar(210), --bits 16 off, 1, 2, 16777216 on, located on group case when index_id = 1 then 'clustered' else 'nonclustered' end + case when ignore_dup_key <>0 then ', ignore duplicate keys' else '' end + case when is_unique <>0 then ', unique' else '' end + case when is_hypothetical <>0 then ', hypothetical' else '' end + case when is_primary_key <>0 then ', primary key' else '' end + case when is_unique_key <>0 then ', unique key' else '' end + case when auto_created <>0 then ', auto create' else '' end + case when no_recompute <>0 then ', stats no recompute' else '' end + ' located on ' + groupname), 'index_keys' = index_keys, --'num_included_columns' = inc_Count, 'included_columns' = inc_columns, 'filter_definition' = filter_definition, 'index_id' = index_id from #spindtab order by index_name return (0) -- sp_helpindexwinc2 GO

Standardize SQL Server Installations with Configuration Files

Standardize SQL Server Installations with Configuration Files

What does my SQL Server data look like over the wire?

What does my SQL Server data look like over the wire?

Thursday, September 22, 2011

Build Hierarchy table from core table

if(object_id('tempdb..#tmp')>1) drop table #tmp declare @depth int = 0 , @count int = 0 create table #tmp (parent_id int, child_id int, depth_from_parent int) SET @depth = 0; TRUNCATE TABLE #tmp; INSERT INTO #tmp(parent_id, child_id, depth_from_parent) VALUES (1, 1, @depth) WHILE @@ROWCOUNT > 0 BEGIN SET @depth = @depth + 1 INSERT INTO #tmp(parent_id, child_id, depth_from_parent) OUTPUT inserted.child_id, inserted.child_id, 0 INTO #tmp SELECT 1, ou.ou_id, os.depth_from_parent + 1 FROM #tmp os (NOLOCK) INNER JOIN ou (NOLOCK) ou ON os.child_id = ou.parent_id WHERE os.depth_from_parent = @depth - 1; END SET @depth = 0 WHILE @@ROWCOUNT > 0 BEGIN SET @depth = @depth + 1; INSERT INTO #tmp(parent_id, child_id, depth_from_parent) SELECT os.parent_id, ou.ou_id, @depth FROM #tmp os INNER JOIN ou (NOLOCK) ON os.child_id = ou.parent_id --AND os.parent_id <> ou.ou_id -- exclude circular reference WHERE os.depth_from_parent = @depth - 1 AND os.parent_id <> 1 END

Wednesday, August 03, 2011

minimum account permissions for service broker

USE USERDB
go

CREATE SCHEMA [office\user] AUTHORIZATION [office\user];

GO
CREATE USER [office\user] WITH DEFAULT_SCHEMA = [office\user];
GRANT CREATE PROCEDURE TO [office\user];
GRANT CREATE QUEUE TO [office\user];
GRANT CREATE SERVICE TO [office\user];
GRANT SUBSCRIBE QUERY NOTIFICATIONS TO [office\user];
GRANT REFERENCES ON CONTRACT::[http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification] TO [office\user];
GRANT RECEIVE ON QueryNotificationErrorsQueue TO [office\user];
GRANT CONTROL ON SCHEMA::[dbo] TO [office\user];
GRANT IMPERSONATE ON USER::DBO TO [office\user];
GO

Monday, June 27, 2011

Parse string characters and separate them

DECLARE @String NVARCHAR(99) = N'abcdefghijk' ;

;WITH Numbers
AS ( SELECT 1 AS Number
UNION ALL
SELECT Number + 1
FROM Numbers
WHERE Number < 99
)
SELECT SUBSTRING(@String, Number, 1) AS SingleChar
FROM Numbers
WHERE Number <= LEN(@String) ;

Parsing Chess FEN string into Board setting

IF OBJECT_ID('TC58','U') IS NOT NULL BEGIN
DROP TABLE TC58
END
GO

CREATE TABLE TC58(
ID INT IDENTITY PRIMARY KEY,
Layout VARCHAR(MAX)
)
GO

--INSERT INTO TC58(Layout) SELECT 'rnbqk2r/ppppbppp/5n2/4p3/2B1P3/5Q2/PPPP1PPP/RNB1K1NR'
--INSERT INTO TC58(Layout) SELECT 'rnbq3r/pppp2pp/8/2ppp3/2B1K3/5P2/PPP2PPP/RNB3NR'
INSERT INTO TC58(Layout) SELECT '4r3/1k6/pN1p4/3P1p1p/3B4/3K1n2/PPP4R/8'-- w - - 7 27
--SELECT * FROM TC58

/*
select
0,
SUBSTRING ( Layout, 0 ,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)) ) ,
CHARINDEX('/',Layout,0) , --8
SUBSTRING ( Layout, CHARINDEX('/',Layout,0)+1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,0) - CHARINDEX('/',Layout,0)) ) ,
CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1) , --17
SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+ 1, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1) -1 ) ,
CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) , --21
SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)- CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) -1) ,
CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1), --25
SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1) -1 ) ,
CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) , --31
SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) +1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - 1 ) ,
CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) , --35
SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) + 1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) -1 ),
CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) , --44
SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) +1 ,LEN(layout) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1))
from TC58
*/

/*
select ID, 8 as RowID , SUBSTRING ( Layout, 0 ,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)) ) from TC58
union all
select ID, 7 as RowID ,SUBSTRING ( Layout, CHARINDEX('/',Layout,0)+1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,0) - CHARINDEX('/',Layout,0)) ) from TC58
union all
select ID, 6 as RowID ,SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+ 1, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1) -1 ) from TC58
union all
select ID, 5 as RowID ,SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)- CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) -1) from TC58
union all
select ID, 4 as RowID ,SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1) -1 ) from TC58
union all
select ID, 3 as RowID ,SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) +1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - 1 ) from TC58
union all
select ID, 2 as RowID ,SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) + 1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) -1 ) from TC58
union all
select ID, 1 as RowID ,SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) +1 ,LEN(layout) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1)) from TC58
*/

/*
select ID, 8 as RowID ,REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, 0 ,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)) ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)) from TC58
union all
select ID, 7 as RowID ,REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,0)+1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,0) - CHARINDEX('/',Layout,0)) ) ,'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)) from TC58
union all
select ID, 6 as RowID ,REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+ 1, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)) from TC58
union all
select ID, 5 as RowID ,REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)- CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) -1),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)) from TC58
union all
select ID, 4 as RowID ,REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)) from TC58
union all
select ID, 3 as RowID ,REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) +1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - 1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)) from TC58
union all
select ID, 2 as RowID ,REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) + 1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)) from TC58
union all
select ID, 1 as RowID ,REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) +1 ,LEN(layout) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1)),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)) from TC58
*/


select ID, 8 as RowID
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, 0 ,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)) ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),1,1) as 'a'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, 0 ,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)) ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),2,1) as 'b'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, 0 ,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)) ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),3,1) as 'c'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, 0 ,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)) ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),4,1) as 'd'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, 0 ,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)) ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),5,1) as 'e'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, 0 ,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)) ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),6,1) as 'f'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, 0 ,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)) ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),7,1) as 'g'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, 0 ,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)) ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),8,1) as 'h'
from TC58
union all
select ID, 7 as RowID
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,0)+1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,0) - CHARINDEX('/',Layout,0)) ) ,'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),1,1) as 'a'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,0)+1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,0) - CHARINDEX('/',Layout,0)) ) ,'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),2,1) as 'b'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,0)+1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,0) - CHARINDEX('/',Layout,0)) ) ,'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),3,1) as 'c'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,0)+1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,0) - CHARINDEX('/',Layout,0)) ) ,'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),4,1) as 'd'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,0)+1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,0) - CHARINDEX('/',Layout,0)) ) ,'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),5,1) as 'e'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,0)+1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,0) - CHARINDEX('/',Layout,0)) ) ,'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),6,1) as 'f'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,0)+1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,0) - CHARINDEX('/',Layout,0)) ) ,'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),7,1) as 'g'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,0)+1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,0) - CHARINDEX('/',Layout,0)) ) ,'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),8,1) as 'h'
from TC58
union all
select ID, 6 as RowID
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+ 1, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),1,1) as 'a'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+ 1, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),2,1) as 'b'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+ 1, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),3,1) as 'c'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+ 1, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),4,1) as 'd'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+ 1, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),5,1) as 'e'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+ 1, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),6,1) as 'f'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+ 1, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),7,1) as 'g'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+ 1, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),8,1) as 'h'
from TC58
union all
select ID, 5 as RowID
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)- CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) -1),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),1,1) as 'a'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)- CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) -1),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),2,1) as 'b'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)- CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) -1),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),3,1) as 'c'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)- CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) -1),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),4,1) as 'd'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)- CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) -1),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),5,1) as 'e'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)- CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) -1),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),6,1) as 'f'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)- CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) -1),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),7,1) as 'g'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)- CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1) -1),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),8,1) as 'h'
from TC58
union all
select ID, 4 as RowID
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),1,1) as 'a'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),2,1) as 'b'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),3,1) as 'c'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),4,1) as 'd'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),5,1) as 'e'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),6,1) as 'f'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),7,1) as 'g'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),8,1) as 'h'
from TC58
union all
select ID, 3 as RowID
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) +1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - 1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),1,1) as 'a'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) +1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - 1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),2,1) as 'b'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) +1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - 1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),3,1) as 'c'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) +1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - 1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),4,1) as 'd'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) +1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - 1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),5,1) as 'e'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) +1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - 1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),6,1) as 'f'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) +1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - 1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),7,1) as 'g'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) +1,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1) - 1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),8,1) as 'h'
from TC58
union all
select ID, 2 as RowID
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) + 1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),1,1) as 'a'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) + 1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),2,1) as 'b'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) + 1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),3,1) as 'c'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) + 1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),4,1) as 'd'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) + 1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),5,1) as 'e'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) + 1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),6,1) as 'f'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) + 1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),7,1) as 'g'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) + 1 , CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1) -1 ),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),8,1) as 'h'
from TC58
union all
select ID, 1 as RowID
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) +1 ,LEN(layout) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1)),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),1,1) as 'a'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) +1 ,LEN(layout) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1)),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),2,1) as 'b'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) +1 ,LEN(layout) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1)),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),3,1) as 'c'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) +1 ,LEN(layout) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1)),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),4,1) as 'd'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) +1 ,LEN(layout) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1)),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),5,1) as 'e'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) +1 ,LEN(layout) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1)),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),6,1) as 'f'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) +1 ,LEN(layout) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1)),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),7,1) as 'g'
,substring(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING ( Layout, CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1) +1 ,LEN(layout) - CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,CHARINDEX('/',Layout,0)+1)+1)+1)+1)+1)+1)),'1',REPLICATE(' ',1)),'2',REPLICATE(' ',2)), '3',REPLICATE(' ',3)), '4',REPLICATE(' ',4)), '5',REPLICATE(' ',5)), '6',REPLICATE(' ',6)), '7',REPLICATE(' ',7)), '8',REPLICATE(' ',8)),8,1) as 'h'
from TC58

Thursday, June 02, 2011

Collect every index from DB to compare

if(OBJECT_ID('tempdb..#tmp')>1)
drop table #tmp
create table #tmp (index_name nvarchar(256), index_description nvarchar(500), index_keys nvarchar(500), included_columns nvarchar(1000),filter_definition nvarchar(256))
if(OBJECT_ID('tempdb..#tmp2')>1)
drop table #tmp2
create table #tmp2 (dbname nvarchar(256), tablename nvarchar(256), index_name nvarchar(256), index_description nvarchar(500), index_keys nvarchar(500), included_columns nvarchar(1000),filter_definition nvarchar(256))

declare @tablename nvarchar(256), @sql nvarchar(4000)
declare tmp_cur cursor for
select name from sys.tables where schema_id = 1

open tmp_cur
Fetch next from tmp_cur into @tablename

while @@fetch_status = 0
begin
print @tablename
set @sql = 'insert into #tmp (index_name , index_description , index_keys , included_columns )
exec sp_helpindex2 '''+@tablename+'''

insert into #tmp2 (dbname , tablename, index_name , index_description , index_keys , included_columns )
select db_name(), '''+@tablename+''' , index_name , index_description , index_keys , included_columns from #tmp

truncate table #tmp
'
print @sql
exec sp_executesql @sql

Fetch next from tmp_cur into @tablename
print '---'
end

close tmp_cur
deallocate tmp_cur

drop table __tmp_all_indexes

select *
into __tmp_all_indexes
from #tmp2

Friday, May 20, 2011

Index - sp_helpindex2 to show include columns

Kimberly L. Tripp | sp_helpindex2 to show included columns (2005+) and filtered indexes (2008) which are not shown by sp_helpindex

Determine SQL Server memory use by database and object

Determine SQL Server memory use by database and object

indexing - List of all index & index columns in SQL Server DB - Stack Overflow

indexing - List of all index & index columns in SQL Server DB - Stack Overflow


--select * from sys.indexes
--select * From sys.index_columns

select
ind.name, ind.index_id, ic.index_column_id, col.name as indexname, t.name as tablename,
ind.*, ic.*, col.*
from
sys.indexes ind
inner join
sys.index_columns ic on
ind.object_id = ic.object_id and ind.index_id = ic.index_id
inner join
sys.columns col on
ic.object_id = col.object_id and ic.column_id = col.column_id
inner join
sys.tables t on
ind.object_id = t.object_id
where
ind.is_primary_key = 0
and ind.is_unique = 0
and ind.is_unique_constraint = 0
and t.is_ms_shipped = 0
and col.name = 'status_id'
and t.name = 'user_lo'
order by
t.name, ind.name, ind.index_id, ic.index_column_id

Friday, April 08, 2011

SQL SERVER – 2005 – Database Table Partitioning Tutorial – How to Horizontal Partition Database Table « Journey to SQLAuthority

SQL SERVER – 2005 – Database Table Partitioning Tutorial – How to Horizontal Partition Database Table « Journey to SQLAuthority

Index fragmentation and re-indexing them

SET NOCOUNT ON;

declare @tbl nvarchar(100) = ''
if(OBJECT_ID('tempdb..#tmp')>1)
drop table #tmp

create table #tmp (servername nvarchar(100),dbname nvarchar(100), tblname nvarchar(100), indexid int, indexname nvarchar(1000), avg_fragmentation_in_percent numeric(15,10), string nvarchar(1000))

declare @mid int , @comid int
declare tmp_cur cursor for
select name From sys.tables where type_desc = 'USER_TABLE' and name not like '[__]%'

open tmp_cur
Fetch next from tmp_cur into @tbl

while @@fetch_status = 0
begin
--print @tbl

--dbcc showcontig(@tbl)
insert into #tmp
SELECT
@@servername,db_name(), @tbl, a.index_id, name, avg_fragmentation_in_percent,
(case
when avg_fragmentation_in_percent < 30 and avg_fragmentation_in_percent > 5 then 'ALTER INDEX '+name+' ON '+@tbl+' REORGANIZE ;'
when avg_fragmentation_in_percent > 30 then 'ALTER INDEX '+name+' ON '+@tbl+' REBUILD WITH (ONLINE=ON) ;'
else 'go'
end)
FROM sys.dm_db_index_physical_stats (DB_ID(), OBJECT_ID(N'dbo.'+@tbl+''),
NULL, NULL, NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;



Fetch next from tmp_cur into @tbl
--print '---'
end

close tmp_cur
deallocate tmp_cur

--select * from #tmp where string != 'go'
----------------------------------------------------

declare @string nvarchar(1000), @avgfrag numeric(20,15), @tblname nvarchar(100), @idx nvarchar(100)
declare tmp_cur cursor for
select string, avg_fragmentation_in_percent,tblname,indexname from #tmp where string != 'go'

open tmp_cur
Fetch next from tmp_cur into @string ,@avgfrag,@tblname,@idx

while @@fetch_status = 0
begin
print '--' +@tblname+' : '+@idx+' : '+convert(nvarchar(20),@avgfrag)

print @string
print 'go'
print 'dbcc dbreindex('''+@tblname+''','''',90)'
print 'go'

print '---'

Fetch next from tmp_cur into @string, @avgfrag,@tblname,@idx
end

close tmp_cur
deallocate tmp_cur

Microsoft SQL Server 2000 Index Defragmentation Best Practices

Microsoft SQL Server 2000 Index Defragmentation Best Practices

Reorganizing and Rebuilding Indexes

Reorganizing and Rebuilding Indexes

Monday, March 28, 2011

function to create a random string

set ANSI_NULLS ON set QUOTED_IDENTIFIER ON
go
create view RandomHelper as select rand( ) as r
GO
CREATE function [dbo].[CreateRandomString]
(
@passwordLength as smallint
)
RETURNS varchar(100)
AS
Begin
DECLARE @password varchar(100)
declare @characters varchar(100)
declare @count int set @characters = ''
-- load up numbers 0 - 9
set @count = 48

while @count <=57
begin
set @characters = @characters + Cast(CHAR(@count) as char(1))
set @count = @count + 1 end
-- load up uppercase letters A - Z
set @count = 65
while @count <=90
begin
set @characters = @characters + Cast(CHAR(@count) as char(1))
set @count = @count + 1 end
-- load up lowercase letters a - z
set @count = 97
while @count <=122
begin
set @characters = @characters + Cast(CHAR(@count) as char(1))
set @count = @count + 1
end
set @count = 0
set @password = ''
while @count < @passwordLength
begin
set @password = @password + SUBSTRING(@characters,CAST((SELECT r FROM RandomHelper)*LEN(@characters) as int)+1,1)
set @count = @count + 1
end
RETURN @password
end
GO

SELECT dbo.CreateRandomString(10)
go

DBCC SHOWCONTIG (Transact-SQL)

DBCC SHOWCONTIG (Transact-SQL)

Friday, March 25, 2011

The Rambling DBA: Jonathan Kehayias : Digging into the SQL Plan Cache: Finding Missing Indexes

The Rambling DBA: Jonathan Kehayias : Digging into the SQL Plan Cache: Finding Missing Indexes



WITH XMLNAMESPACES
(DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan')

SELECT query_plan,
n.value('(@StatementText)[1]', 'VARCHAR(4000)') AS sql_text,
n.value('(//MissingIndexGroup/@Impact)[1]', 'FLOAT') AS impact,
DB_ID(REPLACE(REPLACE(n.value('(//MissingIndex/@Database)[1]', 'VARCHAR(128)'),'[',''),']','')) AS database_id,
OBJECT_ID(n.value('(//MissingIndex/@Database)[1]', 'VARCHAR(128)') + '.' +
n.value('(//MissingIndex/@Schema)[1]', 'VARCHAR(128)') + '.' +
n.value('(//MissingIndex/@Table)[1]', 'VARCHAR(128)')) AS OBJECT_ID,
n.value('(//MissingIndex/@Database)[1]', 'VARCHAR(128)') + '.' +
n.value('(//MissingIndex/@Schema)[1]', 'VARCHAR(128)') + '.' +
n.value('(//MissingIndex/@Table)[1]', 'VARCHAR(128)')
AS statement,
( SELECT DISTINCT c.value('(@Name)[1]', 'VARCHAR(128)') + ', '
FROM n.nodes('//ColumnGroup') AS t(cg)
CROSS APPLY cg.nodes('Column') AS r(c)
WHERE cg.value('(@Usage)[1]', 'VARCHAR(128)') = 'EQUALITY'
FOR XML PATH('')
) AS equality_columns,
( SELECT DISTINCT c.value('(@Name)[1]', 'VARCHAR(128)') + ', '
FROM n.nodes('//ColumnGroup') AS t(cg)
CROSS APPLY cg.nodes('Column') AS r(c)
WHERE cg.value('(@Usage)[1]', 'VARCHAR(128)') = 'INEQUALITY'
FOR XML PATH('')
) AS inequality_columns,
( SELECT DISTINCT c.value('(@Name)[1]', 'VARCHAR(128)') + ', '
FROM n.nodes('//ColumnGroup') AS t(cg)
CROSS APPLY cg.nodes('Column') AS r(c)
WHERE cg.value('(@Usage)[1]', 'VARCHAR(128)') = 'INCLUDE'
FOR XML PATH('')
) AS include_columns
INTO #MissingIndexInfo
FROM
(
SELECT query_plan
FROM (
SELECT DISTINCT plan_handle
FROM sys.dm_exec_query_stats WITH(NOLOCK)
) AS qs
OUTER APPLY sys.dm_exec_query_plan(qs.plan_handle) tp
WHERE tp.query_plan.exist('//MissingIndex')=1
) AS tab (query_plan)
CROSS APPLY query_plan.nodes('//StmtSimple') AS q(n)
WHERE n.exist('QueryPlan/MissingIndexes') = 1

-- Trim trailing comma from lists
UPDATE #MissingIndexInfo
SET equality_columns = LEFT(equality_columns,LEN(equality_columns)-1),
inequality_columns = LEFT(inequality_columns,LEN(inequality_columns)-1),
include_columns = LEFT(include_columns,LEN(include_columns)-1)

SELECT *
FROM #MissingIndexInfo

DROP TABLE #MissingIndexInfo

Find Missing Indexes in Stored Procs with T-SQL « SQL Fool

Find Missing Indexes in Stored Procs with T-SQL « SQL Fool




use master
go

/* Create a stored procedure skeleton */
IF OBJECTPROPERTY(OBJECT_ID('dbo.dba_missingIndexStoredProc_sp'), N'IsProcedure') IS Null
BEGIN
EXECUTE ('Create Procedure dbo.dba_missingIndexStoredProc_sp As Print ''Hello World!''')
RAISERROR('Procedure dba_missingIndexStoredProc_sp created.', 10, 1);
END;
Go

/* Drop our table if it already exists */
IF Exists(SELECT OBJECT_ID FROM sys.tables WHERE [name] = N'dba_missingIndexStoredProc')
BEGIN
DROP TABLE dbo.dba_missingIndexStoredProc
PRINT 'dba_missingIndexStoredProc table dropped!';
END

/* Create our table */
CREATE TABLE dbo.dba_missingIndexStoredProc
(
missingIndexSP_id INT IDENTITY(1,1) Not Null
, databaseName VARCHAR(128) Not Null
, databaseID INT Not Null
, objectName VARCHAR(128) Not Null
, objectID INT Not Null
, query_plan xml Not Null
, executionDate SMALLDATETIME Not Null

CONSTRAINT PK_missingIndexStoredProc
PRIMARY KEY CLUSTERED(missingIndexSP_id)
);

PRINT 'dba_missingIndexStoredProc Table Created';

/* Configure our settings */
SET ANSI_Nulls ON;
SET Quoted_Identifier ON;
Go

ALTER PROCEDURE dbo.dba_missingIndexStoredProc_sp

/* Declare Parameters */
@lastExecuted_inDays INT = 7
, @minExecutionCount INT = 7
, @logResults BIT = 1
, @displayResults BIT = 0

AS
/*********************************************************************************
Name: dba_missingIndexStoredProc_sp

Author: Michelle Ufford, http://sqlfool.com

Purpose: Retrieves stored procedures with missing indexes in their
cached query plans.

@lastExecuted_inDays = number of days old the cached query plan
can be to still appear in the results;
the HIGHER the number, the longer the
execution time.

@minExecutionCount = minimum number of executions the cached
query plan can have to still appear
in the results; the LOWER the number,
the longer the execution time.

@logResults = store results in dba_missingIndexStoredProc

@displayResults = return results to the caller

Notes: This is not 100% guaranteed to catch all missing indexes in
a stored procedure. It will only catch it if the stored proc's
query plan is still in cache. Run regularly to help minimize
the chance of missing a proc.

Called by: DBA and/or SQL Agent Job

Date User Description
----------------------------------------------------------------------------
2009-03-02 MFU Initial Release for public consumption
*********************************************************************************
Exec dbo.dba_missingIndexStoredProc_sp
@lastExecuted_inDays = 30
, @minExecutionCount = 5
, @logResults = 1
, @displayResults = 1;
*********************************************************************************/

SET NOCOUNT ON;
SET XACT_Abort ON;
SET Ansi_Padding ON;
SET Ansi_Warnings ON;
SET ArithAbort ON;
SET Concat_Null_Yields_Null ON;
SET Numeric_RoundAbort OFF;

BEGIN

/* Declare Variables */
DECLARE @currentDateTime SMALLDATETIME;

SET @currentDateTime = GETDATE();

DECLARE @plan_handles TABLE
(
plan_handle VARBINARY(64) Not Null
);

CREATE TABLE #missingIndexes
(
databaseID INT Not Null
, objectID INT Not Null
, query_plan xml Not Null

--CONSTRAINT PK_temp_missingIndexes PRIMARY KEY CLUSTERED
--(
-- databaseID, objectID
--)
);

BEGIN Try

/* Perform some data validation */
IF @logResults = 0 And @displayResults = 0
BEGIN

/* Log the fact that there were open transactions */
EXECUTE dbo.dba_logError_sp
@errorType = 'app'
, @app_errorProcedure = 'dba_missingIndexStoredProc_sp'
, @app_errorMessage = '@logResults = 0 and @displayResults = 0; no action taken, exiting stored proc.'
, @forceExit = 1
, @returnError = 1;

END;

BEGIN TRANSACTION;

/* Retrieve distinct plan handles to minimize dm_exec_query_plan lookups */
INSERT INTO @plan_handles
SELECT DISTINCT plan_handle
FROM sys.dm_exec_query_stats
WHERE last_execution_time > DATEADD(DAY, -@lastExecuted_inDays, @currentDateTime)
And execution_count > @minExecutionCount;

WITH xmlNameSpaces (
DEFAULT 'http://schemas.microsoft.com/sqlserver/2004/07/showplan'
)

/* Retrieve our query plan's XML if there's a missing index */
INSERT INTO #missingIndexes
SELECT deqp.[dbid]
, deqp.objectid
, deqp.query_plan
FROM @plan_handles AS ph
Cross Apply sys.dm_exec_query_plan(ph.plan_handle) AS deqp
WHERE deqp.query_plan.exist('//MissingIndex') = 1
And deqp.objectid IS Not Null;

/* Do we want to store the results of our process? */
IF @logResults = 1
BEGIN
INSERT INTO dbo.dba_missingIndexStoredProc
EXECUTE sp_msForEachDB 'Use [?];
Select ''?''
, mi.databaseID
, Object_Name(o.object_id)
, o.object_id
, mi.query_plan
, GetDate()
From sys.objects As o
Join #missingIndexes As mi
On o.object_id = mi.objectID
Where databaseID = DB_ID();';

END
/* We're not logging it, so let's display it */
ELSE
BEGIN
EXECUTE sp_msForEachDB 'Use [?];
Select ''?''
, mi.databaseID
, Object_Name(o.object_id)
, o.object_id
, mi.query_plan
, GetDate()
From sys.objects As o
Join #missingIndexes As mi
On o.object_id = mi.objectID
Where databaseID = DB_ID();';
END;

/* See above; this part will only work if we've
logged our data. */
IF @displayResults = 1 And @logResults = 1
BEGIN
SELECT *
FROM dbo.dba_missingIndexStoredProc
WHERE executionDate >= @currentDateTime;
END;

/* If you have an open transaction, commit it */
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;

END Try
BEGIN Catch

/* Whoops, there was an error... rollback! */
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;

/* Return an error message and log it */
EXECUTE dbo.dba_logError_sp;

END Catch;

/* Clean-Up! */
DROP TABLE #missingIndexes;

SET NOCOUNT OFF;
RETURN 0;
END
Go


IF OBJECTPROPERTY(OBJECT_ID('dbo.dba_logError_sp'), N'IsProcedure') = 1
BEGIN
DROP PROCEDURE dbo.dba_logError_sp;
PRINT 'Procedure dba_logError_sp dropped';
END;
Go

IF OBJECTPROPERTY(OBJECT_ID('dbo.dba_errorLog'), N'IsTable') IS Null
BEGIN

CREATE TABLE dbo.dba_errorLog
( errorLog_id INT IDENTITY(1,1)
, errorType CHAR(3)
CONSTRAINT [DF_errorLog_errorType] DEFAULT 'sys'
, errorDate DATETIME
CONSTRAINT [DF_errorLog_errorDate] DEFAULT(GETDATE())
, errorLine INT
, errorMessage NVARCHAR(4000)
, errorNumber INT
, errorProcedure NVARCHAR(126)
, procParameters NVARCHAR(4000)
, errorSeverity INT
, errorState INT
, databaseName NVARCHAR(255)
CONSTRAINT PK_errorLog_errorLogID PRIMARY KEY CLUSTERED
(
errorLog_id
)
);

PRINT 'Table dba_errorLog created';

END;
Go


SET ANSI_Nulls ON;
SET Ansi_Padding ON;
SET Ansi_Warnings ON;
SET ArithAbort ON;
SET Concat_Null_Yields_Null ON;
SET NOCOUNT ON;
SET Numeric_RoundAbort OFF;
SET Quoted_Identifier ON;
Go

CREATE PROCEDURE dbo.dba_logError_sp
(
/* Declare Parameters */
@errorType CHAR(3) = 'sys'
, @app_errorProcedure VARCHAR(50) = ''
, @app_errorMessage NVARCHAR(4000) = ''
, @procParameters NVARCHAR(4000) = ''
, @userFriendly BIT = 0
, @forceExit BIT = 1
, @returnError BIT = 1
)
AS
/***************************************************************
Name: dba_logError_sp

Author: Michelle F. Ufford, http://sqlfool.com

Purpose: Retrieves error information and logs in the
dba_errorLog table.

@errorType = options are "app" or "sys"; "app" are custom
application errors, i.e. business logic errors;
"sys" are system errors, i.e. PK errors

@app_errorProcedure = stored procedure name,
needed for app errors

@app_errorMessage = custom app error message

@procParameters = optional; log the parameters that were passed
to the proc that resulted in an error

@userFriendly = displays a generic error message if = 1

@forceExit = forces the proc to rollback and exit;
mostly useful for application errors.

@returnError = returns the error to the calling app if = 1

Called by: Another stored procedure

Date Initials Description
----------------------------------------------------------------------------
2008-12-16 MFU Initial Release
****************************************************************
Exec dbo.dba_logError_sp
@errorType = 'app'
, @app_errorProcedure = 'someTableInsertProcName'
, @app_errorMessage = 'Some app-specific error message'
, @userFriendly = 1
, @forceExit = 1
, @returnError = 1;
****************************************************************/

SET NOCOUNT ON;
SET XACT_Abort ON;

BEGIN

/* Declare Variables */
DECLARE @errorNumber INT
, @errorProcedure VARCHAR(50)
, @dbName sysname
, @errorLine INT
, @errorMessage NVARCHAR(4000)
, @errorSeverity INT
, @errorState INT
, @errorReturnMessage NVARCHAR(4000)
, @errorReturnSeverity INT
, @currentDateTime SMALLDATETIME;

DECLARE @errorReturnID TABLE (errorID VARCHAR(10));

/* Initialize Variables */
SELECT @currentDateTime = GETDATE();

/* Capture our error details */
IF @errorType = 'sys'
BEGIN

/* Get our system error details and hold it */
SELECT
@errorNumber = Error_Number()
, @errorProcedure = Error_Procedure()
, @dbName = DB_NAME()
, @errorLine = Error_Line()
, @errorMessage = Error_Message()
, @errorSeverity = Error_Severity()
, @errorState = Error_State() ;

END
ELSE
BEGIN

/* Get our custom app error details and hold it */
SELECT
@errorNumber = 0
, @errorProcedure = @app_errorProcedure
, @dbName = DB_NAME()
, @errorLine = 0
, @errorMessage = @app_errorMessage
, @errorSeverity = 0
, @errorState = 0 ;

END;

/* And keep a copy for our logs */
INSERT INTO dbo.dba_errorLog
(
errorType
, errorDate
, errorLine
, errorMessage
, errorNumber
, errorProcedure
, procParameters
, errorSeverity
, errorState
, databaseName
)
OUTPUT Inserted.errorLog_id INTO @errorReturnID
VALUES
(
@errorType
, @currentDateTime
, @errorLine
, @errorMessage
, @errorNumber
, @errorProcedure
, @procParameters
, @errorSeverity
, @errorState
, @dbName
);

/* Should we display a user friendly message to the application? */
IF @userFriendly = 1
SELECT @errorReturnMessage = 'An error has occurred in the database (' + errorID + ')'
FROM @errorReturnID;
ELSE
SELECT @errorReturnMessage = @errorMessage;

/* Do we want to force the application to exit? */
IF @forceExit = 1
SELECT @errorReturnSeverity = 15
ELSE
SELECT @errorReturnSeverity = @errorSeverity;

/* Should we return an error message to the calling proc? */
IF @returnError = 1
RAISERROR
(
@errorReturnMessage
, @errorReturnSeverity
, 1
) WITH NoWait;

SET NOCOUNT OFF;
RETURN 0;

END
Go

Thursday, February 17, 2011

ESSENTIAL PERFORMANCE TOOLS FOR SQL SERVER DBA

http://www.idera.com/Downloads/WhitePapers/Essential-Performance-Tools-SQL-Server-DBA.pdf?elq=365bc336c7cf4d3aaa5ec818146aa0a9

Thursday, January 27, 2011

Find Clustered Indexes that are uniqueidentifier field

SELECT
OBJECT_NAME(i.ID) as tablename
,ISNULL(SYSCOLUMNS.NAME,'') as columnname
,i.name as indexname
, i.indid as isclustered
,systypes.name as columndatatype
--,*
FROM SYSINDEXES I
INNER JOIN SYSINDEXKEYS ON I.ID=SYSINDEXKEYS.ID AND I.INDID=SYSINDEXKEYS.INDID
INNER JOIN SYSCOLUMNS ON SYSINDEXKEYS.ID=SYSCOLUMNS.ID AND SYSINDEXKEYS.COLID=SYSCOLUMNS.COLID
inner join systypes on systypes.xtype = SYSCOLUMNS.xtype
inner join sysobjects on sysobjects.id = i.id
WHERE I.INDID =1
AND I.INDID < 255 AND (I.STATUS & 64)=0 and SYSCOLUMNS.xtype = 36 and i.id > 255
and sysobjects.xtype = 'U'
order by
OBJECT_NAME(i.ID)

Leaving a SQL Server DBA Job Gracefully

Leaving a SQL Server DBA Job Gracefully

Tuesday, January 25, 2011

drop indexes for all tables in DB

sp_msforeachtable
'

declare @name varchar(50) ,@errorsave int, @tab_name varchar(100) = ''?''


if exists (select name from sysindexes
where id = object_id(@tab_name) and indid > 0 and indid < 255 and (status & 64)=0) begin declare ind_cursor cursor for select name from sysindexes where id = object_id(@tab_name) and indid > 0 and indid < 255 and (status & 64)=0

open ind_cursor
fetch next from ind_cursor into @name
while (@@fetch_status = 0)
begin
print ''drop index '' + @tab_name + ''.'' + @name
print ''go''
fetch next from ind_cursor into @name
end
close ind_cursor
deallocate ind_cursor
end

'

Monday, January 24, 2011

sp_alert_jobs

USE [msdb]
GO
/****** Object: StoredProcedure [dbo].[sp_alert_jobs] Script Date: 01/24/2011 07:50:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create procedure [dbo].[sp_alert_jobs]
(
@maxrundurationhour int = 6
)
as
begin

--CAN NOT EXECUTE THIS PROC BY QUERY , ONLY RUNS FROM JOB

if(object_id('msdb..#tmp')>1)
drop table #tmp
if(object_id('msdb..__tmp_final')>1)
drop table __tmp_final


declare @maxrunduration int = 0
--set @maxrunduration = 60 * 60 * 6 -- 6 hours
set @maxrunduration = 60 * 60 * @maxrundurationhour

create table #tmp (job_id uniqueidentifier NOT NULL,last_run_date nvarchar (20) NOT NULL,last_run_time nvarchar (20) NOT NULL,next_run_date nvarchar (20) NOT NULL,next_run_time nvarchar (20) NOT NULL, next_run_schedule_id INT NOT NULL,requested_to_run INT NOT NULL,request_source INT NOT NULL,request_source_id sysname COLLATE database_default NULL, running INT NOT NULL,current_step INT NOT NULL,current_retry_attempt INT NOT NULL,job_state INT NOT NULL);

insert into #tmp EXECUTE master.dbo.xp_sqlagent_enum_jobs 1,'CSODProd\SQLClusterLD4SW2';
UPDATE #tmp SET last_run_time = right ('000000' + last_run_time, 6), next_run_time = right ('000000' + next_run_time, 6);

--select * From #tmp

SELECT @@servername as ServerName , j.name AS JobName, j.enabled AS Enabled,
Case x.running WHEN 1 THEN 'Running' Else Case h.run_status WHEN 2 THEN 'Inactive' WHEN 4 THEN 'Inactive' Else 'Completed' End End AS CurrentStatus,
coalesce (x.current_step, 0) AS CurrentStepNbr,
CASE WHEN x.last_run_date > 0 THEN convert (datetime, substring (x.last_run_date, 1, 4)+ '-' + substring (x.last_run_date, 5, 2)+ '-'+ substring (x.last_run_date, 7, 2)+ ' '+ substring (x.last_run_time, 1, 2) + ':' + substring (x.last_run_time, 3, 2)+ ':' + substring (x.last_run_time, 5, 2)+ '.000',121) Else NULL End AS LastRunTime,
Case h.run_status WHEN 0 THEN 'Fail'WHEN 1 THEN 'Success' WHEN 2 THEN 'Retry' WHEN 3 THEN 'Cancel' WHEN 4 THEN 'In progress' End AS LastRunOutcome,
CASE WHEN h.run_duration > 0 THEN (h.run_duration / 1000000) * (3600 * 24) + (h.run_duration / 10000 % 100) * 3600 + (h.run_duration / 100 % 100) * 60 + (h.run_duration % 100) Else NULL End AS LastRunDuration
into __tmp_final
FROM #tmp x
Left Join msdb.dbo.sysjobs j ON x.job_id = j.job_id
LEFT OUTER JOIN msdb.dbo.syscategories c ON j.category_id = c.category_id
LEFT OUTER JOIN msdb.dbo.sysjobhistory h ON x.job_id = h.job_id AND x.last_run_date = h.run_date AND x.last_run_time = h.run_time AND h.step_id = 0
where --j.name like 'csod%'
h.run_status != 1
or h.run_duration > @maxrunduration

--select * from __tmp_final
--select 'Job = '+jobname+' : Status = '+lastrunoutcome+ ' : Run Duration = '+ convert(nvarchar(10),lastrunduration)+' min' from __tmp_final
if(select COUNT(*) from __tmp_final) >0
begin
declare @subject nvarchar(1000), @recipientslist nvarchar(1000)
set @subject = 'SQL JOB ALERT for '+@@SERVERNAME+' : '+Convert(nvarchar(100),getdate(),101)
set @recipientslist = 'ayegudkin@csod.com;palexander@csod.com;Defcon4@csod.com'

exec msdb.dbo.sp_send_dbmail
@body_format = 'HTML',
@profile_name = 'default',
@Subject = @subject,
--@body = 'test',
@query = 'set nocount on; select ''Job = ''+jobname+'' : Status = ''+lastrunoutcome+ '' : Run Duration = ''+ convert(nvarchar(10),lastrunduration)+'' min
'' from __tmp_final;set nocount off; ',
--@attach_query_result_as_file = 0,
@query_result_header = 0,
--@query_result_width = 1000,
--@exclude_query_output = 1,
--@query_result_separator = ';',
@execute_query_database = 'msdb',
@recipients = @recipientslist
end
--EXEC sys.xp_logininfo @acctname = 'CSODMGMT\palexander', @option ='members'
--EXEC sys.xp_logininfo @acctname = 'CSODProd\SQLClusterLA4SW4'


end

Monday, January 10, 2011

Run an SSIS Package Under a Different Account - SQLServerCentral

Run an SSIS Package Under a Different Account - SQLServerCentral


Run an SSIS Package Under a Different Account
By Polar Bear, 2010/03/25
Total article views: 6535 | Views in the last 30 days: 88
Rate this | Join the discussion | Briefcase | Print
Recently, in a SSIS package, I needed to get some data from a SQL Server database which is used by a third party application. This application uses named user license. The ETLadmin account, which is a domain account that we use it to run SSIS packages, does not have the right permission to access views in that database even if it has sysadmin permission on that SQL Server instance. If we set ETLadmin to an application admin, this will waste an application admin license. And usually ETLadmin account should only have read permission to grab data. Application admin permission will be too much for this account. It will be nice if we can use an existing application admin user account to run the package. This can be done by using SQL Server Agent proxies.

Here are the steps to setup a proxy by using an existing application user account:

Create a credential using the account that having right access to the application database

Open SSMS, connect to the SQL Server instance that the SSIS will be scheduled to run
Go to Security - > Credentials, and click on 'New Credential...' to create a new credential


Zoom in | Open in new window
Enter the credential name - Enter the domain account, and password. Repeat the password in the 'Confirm password'. This account should have the right access to the application database.
Click 'ok' and the new credential should be listed.

Zoom in | Open in new window
Create a proxy using the credential created in the previous step

Right click SQL Server Agent -> Proxies, and select 'New proxy...'

Zoom in | Open in new window
Enter the new proxy name, and choose the credential that created from the previous step from the dropdown list. And check 'SQL Server Integration Services Package' under 'Active to the following subsystems'. The SQL Server Agent proxy can be activated for many sub systems (as listed in the screen shot). In this case we are only enabling it for SSIS packages.

Zoom in | Open in new window
Click 'OK' and the new proxy should be listed.
Setup a job to run the SSIS package using the proxy

Open the job step properties for the step that run the SSIS package
Select the proxy that created in the previous step from the 'Run as' dropdown list

Zoom in | Open in new window
Click 'OK' to save the change
Now you can run the package using the application account.

By using SQL Server Agent proxy, we can run jobs on different databases, different servers using existing accounts, and avoid giving excessive permission to ETL users or developers.