Friday, April 13, 2012

Excel compare columns

Sub Compare2Cols()

' Principals

' For x = 1 To 32 Step 4

' For y = 2 To 106

' Cost Centers

' For x = 1 To 83 Step 4

' For y = 2 To 78

' Levels

' For x = 5 To 8 Step 2

' For y = 2 To 32

For x = 5 To 8 Step 2

For y = 2 To 32

'For show ...

Cells(y, x).Select

If Cells(y, x) <> Cells(y, x + 1) Then

With Cells(y, x).Interior

.Pattern = xlSolid

.PatternColorIndex = xlAutomatic

.Color = 65535

.TintAndShade = 0

.PatternTintAndShade = 0

End With

With Cells(y, x + 1).Interior

.Pattern = xlSolid

.PatternColorIndex = xlAutomatic

.Color = 65535

.TintAndShade = 0

.PatternTintAndShade = 0

End With

Else

With Cells(y, x).Interior

.Pattern = xlNone

.TintAndShade = 0

.PatternTintAndShade = 0

End With

With Cells(y, x + 1).Interior

.Pattern = xlNone

.TintAndShade = 0

.PatternTintAndShade = 0

End With

End If

Next y

Next x

Cells(y, x).Select

End Sub

Thursday, April 12, 2012

Search Every Column in Every Table

-- Update to exclude image and other blob types

SELECT 'SELECT [' + COLUMN_NAME + '] ''[' + TABLE_CATALOG + '].[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'' FROM [' + TABLE_CATALOG + '].[' + TABLE_SCHEMA + '].[' + TABLE_NAME + '] WHERE CAST ([' + COLUMN_NAME + '] AS VARCHAR (MAX)) like ''%86110%''' FROM INFORMATION_SCHEMA.Columns c

Wednesday, March 28, 2012

TSQL Script to identify unused indexes

http://beyondrelational.com/modules/30/scripts/485/scripts/11430/tsql-script-to-identify-unused-indexes.aspx?utm_source=brnewsletter&utm_medium=email&utm_campaign=2012Mar

WITH cte AS (
02.SELECT
03.'['+ c.name + '].[' + o.name + ']' AS TableName,
04.i.name AS IndexName,
05.i.index_id AS IndexID,
06.user_seeks + user_scans + user_lookups AS Reads,
07.user_updates AS Writes,
08.(
09.SELECT SUM(p.rows)
10.FROM sys.partitions p
11.WHERE p.index_id = s.index_id
12.AND s.object_id = p.object_id
13.) AS TotalRows,
14.CASE
15.WHEN s.user_updates < 1 THEN 100
16.ELSE 1.00 * (s.user_seeks + s.user_scans + s.user_lookups)
17./ s.user_updates
18.END AS ReadsPerWrite,
19.'DROP INDEX ' + QUOTENAME(i.name)
20.+ ' ON ' + QUOTENAME(c.name)
21.+ '.' + QUOTENAME(OBJECT_NAME(s.object_id))
22.AS 'DropSQL'
23.FROM sys.dm_db_index_usage_stats s
24.INNER JOIN sys.indexes i ON i.index_id = s.index_id
25.AND s.object_id = i.object_id
26.INNER JOIN sys.objects o on s.object_id = o.object_id
27.INNER JOIN sys.schemas c on o.schema_id = c.schema_id
28.WHERE OBJECTPROPERTY(s.object_id,'IsUserTable') = 1
29.AND s.database_id = DB_ID()
30.AND i.type_desc = 'nonclustered'
31.AND i.is_primary_key = 0
32.AND i.is_unique_constraint = 0
33.AND
34.(
35.SELECT SUM(p.rows)
36.FROM sys.partitions p
37.WHERE p.index_id = s.index_id
38.AND s.object_id = p.object_id
39.) > 10000
40.)
41.SELECT * FROM cte
42./*
43.TableName Name ID Reads Writes Rows ReadsPerWrite DropSQL
44.---------- ----- -- ------- ------ ----- ------------- -------
45.[dbo].[t1] IDX_1 20 1227972 996081 78599 1.23280335635 DROP ..
46.[dbo].[t2] IDX_2 21 51359 33912 78599 1.51447865062 DROP ..
47.[dbo].[t3] IDX_3 22 235280 159808 78599 1.47226672006 DROP ..
48.*/

Friday, March 16, 2012

Find Non-numeric Rows in Column

CREATE TABLE #foo (

ident BIGINT IDENTITY (0, 1)

, someString VARCHAR (128) DEFAULT '')

INSERT #foo ( someString )

SELECT '4546546'

UNION

SELECT '456654.475'

UNION

SELECT 'afafsdf'

UNION

SELECT '78998'

UNION

SELECT '87979z'

SELECT ident

, someString

, PATINDEX ('%[^0-9]%', someString)

FROM #foo

WHERE PATINDEX ('%[^0-9]%', someString) != 0

Tuesday, March 13, 2012

Dump Database

Find/export all data in database

SELECT 'SELECT ''' + c.TABLE_CATALOG + '.' + c.TABLE_SCHEMA + '.' + c.TABLE_NAME + '.' + c.COLUMN_NAME + ''', * FROM ['
+ c.TABLE_CATALOG + '].[' + c.TABLE_SCHEMA + '].[' + c.TABLE_NAME
+ '] WHERE [' + c.COLUMN_NAME + '] LIKE ''%dss20%'' OR [' + c.COLUMN_NAME + '] LIKE ''%MCEPSIWDB001%'' OR [' + c.COLUMN_NAME + '] LIKE ''%MCEPSIWWS001%'''
FROM INFORMATION_SCHEMA.columns c
JOIN INFORMATION_SCHEMA.tables t
ON t.TABLE_CATALOG = c.TABLE_CATALOG
AND t.TABLE_SCHEMA = c.TABLE_SCHEMA
AND t.TABLE_NAME = c.TABLE_NAME
WHERE c.DATA_TYPE LIKE '%char%'
AND t.TABLE_TYPE = 'BASE TABLE'

Wednesday, February 29, 2012

Table / Column Search

SELECT

c.TABLE_NAME

, c.COLUMN_NAME

FROM INFORMATION_SCHEMA.TABLES t

JOIN INFORMATION_SCHEMA.COLUMNS c

ON t.TABLE_CATALOG = c.TABLE_CATALOG

AND t.TABLE_SCHEMA = c.TABLE_SCHEMA

AND t.TABLE_NAME = c.TABLE_NAME

AND t.TABLE_TYPE = 'BASE TABLE'

WHERE c.COLUMN_NAME LIKE '%user%'

Really - I'm Not a DBA :: Custom DB Permissions: user - schema - db - login Part 2

Example test scripts for "Really - I'm Not a DBA :: Custom DB Permissions: user - schema - db - login Part 1"


USE TargetDB
GO

-- Server: SERVER
-- DB: TargetDB


SET NOCOUNT ON

-- should work
SELECT 'WORK: CREATE TABLE bud.jkTest_UserA'
CREATE TABLE bud.jkTest_UserA (aVC VARCHAR (128), bINT int)
GO

-- should FAIL
SELECT 'FAIL: CREATE TABLE pa.jkTest_UserA'
CREATE TABLE pa.jkTest_UserA (aVC VARCHAR (128), bINT int)
GO

-- should FAIL
SELECT 'FAIL: CREATE TABLE UCSF_SYSTEM.dbo.jkTest_UserA'
CREATE TABLE UCSF_SYSTEM.dbo.jkTest_UserA (aVC VARCHAR (128), bINT int)
GO

-- should work
SELECT 'WORK: INSERT bud.jkTest_UserA'
INSERT bud.jkTest_UserA (aVC, bINT)
SELECT SUSER_NAME(), 1
GO

-- should work
SELECT 'WORK: INSERT bud.jkTest'
INSERT bud.jkTest (aVC, bINT)
SELECT SUSER_NAME(), 1
GO

-- should FAIL
SELECT 'FAIL: INSERT pa.jkTest'
INSERT pa.jkTest (aVC, bINT)
SELECT SUSER_NAME(), 1
GO

-- should FAIL
SELECT 'FAIL: INSERT UCSF_SYSTEM.dbo.jkTest '
INSERT UCSF_SYSTEM.dbo.jkTest (aVC, bINT)
SELECT SUSER_NAME(), 1
GO

-- should work
SELECT 'WORK: SELECT * FROM bud.jkTest '
SELECT * FROM bud.jkTest
GO

-- should work
SELECT 'WORK: SELECT * FROM pa.jkTest '
SELECT * FROM pa.jkTest
GO

-- should work
SELECT 'WORK: SELECT TOP 33 * FROM TARGETDB.dbo.T_Name '
SELECT TOP 33 * FROM TARGETDB.dbo.T_Name
GO

Friday, February 17, 2012

Last Time Tables Used - Referenced

http://beyondrelational.com/modules/1/justlearned/388/tips/9111/sql-server-finding-last-accessed-time-for-tables-by-queries-or-find-unused-tables.aspx?utm_source=brnewsletter&utm_medium=email&utm_campaign=2012Feb


Requires 8.0 compatibility.

--select su.[admin] from sys_users su where su.username like 'kellyjoe%'

-- update su set su.[admin] = 0 from sys_users su where su.username like 'kellyjoe%'
WITH LastActivity (ObjectID, LastAction)
AS
(
SELECT object_id AS TableName, Last_User_Seek as LastAction
FROM sys.dm_db_index_usage_stats u
WHERE database_id = db_id(db_name())
UNION
SELECT object_id AS TableName,last_user_scan as LastAction
FROM sys.dm_db_index_usage_stats u
WHERE database_id = db_id(db_name())
UNION
SELECT object_id AS TableName,last_user_lookup as LastAction
FROM sys.dm_db_index_usage_stats u
WHERE database_id = db_id(db_name())
)
SELECT OBJECT_NAME(so.object_id)AS TableName,
MAX(la.LastAction)as LastSelect
FROM
sys.objects so
LEFT JOIN LastActivity la
ON so.object_id = la.ObjectID
WHERE so.type = 'U'
AND so.object_id > 100 --returns only the user tables.Tables with objectid<100 are systables.
GROUP BY OBJECT_NAME(so.object_id)
ORDER BY OBJECT_NAME(so.object_id)

Monday, February 6, 2012

Proc Name from Within Proc

http://www.sqldbpros.com/2011/01/sql-server-get-proc-name-from-within-proc/

SQL Server – Get Proc Name From Within Proc

Want to get the name of a SQL Server stored procedure from with the procedure itself? No problem! This quick T-SQL script is all you need.

SELECT OBJECT_NAME(@@PROCID)

Need the schema as well?

SELECT OBJECT_SCHEMA_NAME(@@PROCID), OBJECT_NAME(@@PROCID)

I've found this particularly helpful when logging stored procedure execution to an audit table.

p.s. I think this goes without saying but if you need only the object id the following complicated query can be used:

SELECT @@PROCID

Wednesday, January 18, 2012

How to debug ActiveX dll’s (VB6)

How to debug ActiveX dll’s (VB6)

1.) Get the method call, i.e. getDetails("1206", "1601001", "guya", "2", vTable, WriteAccess, RowCount)
2.) Open VB project, change project properties from “ActiveX DLL” to “Standard EXE” and start-up object to “Sub Main”
3.) Add in a Sub Main constructor, doing so in a *.bas (not *.class) module is fine

Public Sub Main()

' Note that switching from an ActiveX DLL to a Standard EXE may/will change the ' class module “Instancing” property from “Multiuse” to “Private” (error: “No
' creatable public component detected". To get back to the ActiveX DLL change the ' class module “Instancing” property back to “Multiuse”

Dim sError, vTable, WriteAccess, RowCount
‘ name of class that contains the function to invoke

Dim foo As New cReports

‘ invoke function
sError = foo.getDetails("1206", "1601001", "guya", "2", vTable, WriteAccess, RowCount)

‘F8 – away!

‘modal for a breakpoint
MsgBox Command$, vbOK, "Command Line params"

End Sub

Tuesday, January 10, 2012

SQL Regex

http://beyondrelational.com/justlearned/posts/763/find-column-names-which-has-special-characters.aspx?utm_source=brnewsletter&utm_medium=email&utm_campaign=2012Jan

USE[]
02.GO
03.
04.SELECT tab.TABLE_NAME,col.COLUMN_NAME
05.FROM INFORMATION_SCHEMA.COLUMNS col
06.INNER JOIN INFORMATION_SCHEMA.TABLES tab
07.ON tab.Table_name = col.TABLE_NAME
08.WHERE tab.TABLE_TYPE = 'BASE TABLE'
09.AND
10.col.COLUMN_NAME LIKE '%[^a-zA-Z0-9]%'

Wednesday, January 4, 2012

SQL Server Table and Column with Extended Properties

USE FooBar
GO

CREATE TABLE dbo.tFoo (
ident INT IDENTITY (1, 1)
, PayCode CHAR (4) NOT NULL PRIMARY KEY
, GroupCode CHAR (16) DEFAULT ''
, GroupCodeDescription VARCHAR (256) DEFAULT ''
, crDate DATETIME DEFAULT GETDATE ()
, uDate DATETIME DEFAULT GETDATE ()
)

EXEC sys.sp_addextendedproperty
@name = N'tFoo - Purpose',
@value = N'Provide a logical extension to tBar without breaking any unknown unqualified inserts and provide a way to alert of any new paycodes that require a group association.',
@level0type = N'SCHEMA',
@level0name = N'dbo',
@level1type = N'TABLE',
@level1name = N'tFoo';
GO

EXEC sys.sp_addextendedproperty
@name = N'tFoo - PayCode',
@value = N'PayCode is the primary key and the foreign key to fBar.',
@level0type = N'SCHEMA',
@level0name = N'dbo',
@level1type = N'TABLE',
@level1name = N'tFoo',
@level2type = N'COLUMN',
@level2name = N'PayCode';
GO

Friday, December 9, 2011

WaitFor Delay

ALTER PROC Portal.WaitForStub (@seconds BIGINT)
AS
BEGIN

/****************************************************************************
Joe Kelly
2011-12-09 14:03:18.870

Stub method to simulate a long-running process up to a day.

Input is in seconds.

EXEC Portal.WaitForStub 3

****************************************************************************/

SET NOCOUNT ON

DECLARE @time DATETIME
SELECT @time = CAST((@seconds / 3600) AS VARCHAR(2)) + ':' + CAST((@seconds / 60) AS VARCHAR(2)) + ':' + CAST((@seconds % 60) AS VARCHAR(2))

WAITFOR DELAY @time


END

Monday, November 14, 2011

Get Columns in Table

http://beyondrelational.com/justlearned/posts/792/sql-server-to-get-comma-separated-value-for-every-column-name-in-tables-with-t-sql.aspx

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+', ' ,'') + Name
FROM sys.columns
WHERE OBJECT_NAME(OBJECT_ID)='dat_groups'
SELECT @listStr

Wednesday, November 9, 2011

T-SQL Count Spaces in String

http://stanbiron.com/2010/07/29/SimpleWayToCountCharactersAndWordsUsingTSQL.aspx

-- Count the number of words

DECLARE @String VARCHAR(100)

SELECT @String = 'SQL Server 2005 Stan test code'

SELECT LEN(@String) - LEN(REPLACE(@String, ' ', '')) + 1

Wednesday, November 2, 2011

Longest Running Queries

http://www.sqlservercentral.com/Forums/Topic619606-360-1.aspx#bm1151148

SELECT TOP 100
qs.total_elapsed_time / qs.execution_count / 1000000.0 average_seconds
, qs.total_elapsed_time / 1000000.0 total_seconds
, qs.execution_count
, SUBSTRING (qt.text,qs.statement_start_offset/2
, ( CASE
WHEN qs.statement_end_offset = -1
THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
ELSE qs.statement_end_offset
END - qs.statement_start_offset
)/2
) individual_query
, o.name object_name
, DB_NAME(qt.dbid) database_name
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
LEFT OUTER JOIN sys.objects o
ON qt.objectid = o.object_id
WHERE qt.dbid = DB_ID()
ORDER BY average_seconds DESC

SSMS REGEX - Remove Carriage Returns

http://www.simple-talk.com/sql/sql-training/regex-based-finding-and-replacing-of-text-in-ssms/

\n @\n
\n

SQL Regex

http://beyondrelational.com/blogs/naomi/archive/2011/10/19/remove-bad-characters-from-a-string.aspx?utm_source=brnewsletter&utm_medium=email&utm_campaign=2011Nov02

01.CREATE FUNCTION dbo.RemoveBadChars
02. (@String VARCHAR(8000),
03. @AllowedPattern VARCHAR(100))
04.RETURNS VARCHAR(8000)
05.AS
06. BEGIN
07. DECLARE @nBadChars INT,
08. @Rest VARCHAR(100)
09.
10. SET @String = '!@#$% 123 ??abc##rd,,,'
11.
12. SET @nBadChars = Patindex('%[^' + @AllowedPattern + ']%',@String)
13.
14. WHILE @nBadChars > 0
15. BEGIN
16. SET @Rest = Substring(@String,@nBadChars + 1,Len(@String))
17.
18. SET @String = Substring(@String,1,@nBadChars - 1)
19.
20. SET @Rest = Substring(@Rest,Patindex('%[' + @AllowedPattern + ']%',@Rest),
21. Len(@Rest))
22.
23. SET @String = @String + @Rest
24.
25. SET @nBadChars = Patindex('%[^' + @AllowedPattern + ']%',@String)
26. END
27.
28. RETURN @String
29. END
30.
31.GO



1.SELECT dbo.RemoveBadChars('1234@@@@@@@@@????????djwkejwk^&*-+=a',' 0-9a-z')

Friday, October 28, 2011

Wednesday, October 19, 2011

SQL Server Good Guidance on Missing Indices

http://beyondrelational.com/blogs/martinschmidt/archive/2011/09/27/missing-indexes.aspx?utm_source=brnewsletter&utm_medium=email&utm_campaign=2011Oct18 One of the most common things I encounter when asked to help with performance problems, is wrong or inadequate indexing. Creating the optimal indexes for a system, is no where near a trivial excercise. You need to consider the read/write ratio as well as how you write your queries. This is not the scope of this blog post. SQL Server has a number of dynamic management views/functions, which is very useful for different purposes. At least if you know they are there, and how to use them. For missing index information, these views are important: view source print? 1.SELECT * FROM sys.dm_db_missing_index_group_stats 2.SELECT * FROM sys.dm_db_missing_index_details 3.SELECT * FROM sys.dm_db_missing_index_groups sys.dm_db_missing_index_group_stats tracks information about indexes which could have been useful to the SQL Server. It holds information about how many times the SQL Server could have used that index, and how great an impact it would have had on the query. This DMV does not give you the details about the table and columns that the index should have been created on. This is however available in the sys.dm_db_missing_index_details DMV, where you get information about the database_id, object_id and the columns in the index. The last DMV is only used to bind the two DMV’s together. The DMV’s contains data on server level, so it will show details about missing index in all your databases. Let me show how a basic query on these DMV’s could look like: view source print? 1.SELECT * 2.FROM 3. sys.dm_db_missing_index_groups g 4. INNER JOIN sys.dm_db_missing_index_group_stats gs ON gs.group_handle = g.index_group_handle 5. INNER JOIN sys.dm_db_missing_index_details d ON g.index_handle = d.index_handle On my local SQL Server, this gives me an empty resultset: So, let me create some test data: view source print? 01.CREATE DATABASE IndexDemo 02.GO 03.USE IndexDemo 04.GO 05.CREATE TABLE DemoData ( 06. Id INT IDENTITY PRIMARY KEY, 07. Val1 INT, 08. Val2 INT, 09. Val3 CHAR(4000) 10.) 11.GO 12.INSERT INTO DemoData (Val1, Val2, Val3) 13.VALUES (1,1, '') 14.GO 15. 16.INSERT INTO DemoData (Val1, Val2, Val3) 17.SELECT Val1, Val2, Val3 18.FROM DemoData 19.GO 15 I have created a table with a clustered index on the Id column, and filled the table with 32K rows. Now I will create a query to return the Id and Val1 column, given a specific value for Val2: view source print? 1.SELECT Id, Val1 2.FROM DemoData 3.WHERE Val2 = 123 So, now let me try to run the missing index query again, but this time only looking at a limited number of columns: view source print? 01.SELECT 02. user_seeks, 03. last_user_seek, 04. avg_total_user_cost, 05. avg_user_impact, 06. database_id, 07. object_id, 08. equality_columns, 09. inequality_columns, 10. included_columns 11.FROM 12. sys.dm_db_missing_index_groups g 13. INNER JOIN sys.dm_db_missing_index_group_stats gs ON gs.group_handle = g.index_group_handle 14. INNER JOIN sys.dm_db_missing_index_details d ON g.index_handle = d.index_handle Now one row is returned. Let’s go through the returned columns, and see what the values mean: user_seeks This tells you how many times the SQL Server could have used this missing index to lookup data. The higher this number is, the more reason to build the index. How high this is, depends on your system. On high volume OLTP setups, numbers of less the 10.000 is not worth worrying about, and on smaller systems a value of 20-100 might be high enough to consider the index. last_user_seek This tells you when the missing index was last needed. If this value is equal to last saturday at night, it _could_ mean that you have a nightly job running on saturday, which might need this index. avg_total_user_cost This value does not have a unit, but it’s a value that tells you something about the estimated cost of the queries that needed the index. The higher the value is, the more resource intensive is the query that needs the index. If the value is very low (perhaps 0.01) then the query that needed the index was not very resource intensive. Think of a query that executes in 2ms compared to a query that takes 2000ms. You will probably gain more by adding an index to satisfy the 2000ms query than the 2ms one. avg_user_impact This is the expected improvement of the query if you build the query. The closer the value is to 100, the more the query will benefit from building the index. database_id This is the database where you need to build the index. object_id This is the object_id of the table that could need an index. equality_columns These columns are the ones that you should build the index on. Equality columns means that the predicate used the column like this: “Val2 = x”, which was exactly how I wrote my demo query. inequality_columns You should also add these columns to your index. Inequality columns are used for range predicates, like: “Val2 > x”. My missing index query returned NULL in this column, because my demo query had no such predicate. included_columns If columns are used in the SELECT part of your query, and not in the predicate, you can add these columns as included columns in the index. This way all needed data is available in the index, and no key lookup is needed on the clustered index. But beware! The more columns you add to your index, the more write IO and space you need. My rule of thumb says, that the total number of columns (equality_columns + inequality_columns + included_columns) should not exceed 5. If the total number of columns exceeds 5, that does not mean that you should not build the index – it just means that you need to think carefully about what you are doing! So, normally I run this query, and returns the rows ordered by user_seeks desc. Then I look at the top 10-20 rows, and see if any of them have avg_user_impact in the 90-100 range. Then I look for the number of columns in the index, and then I decide whether or not the index should be build. This is NOT a query that gives you the answer to everything, but it can definately help you spot the indexes that you should add to your system. Finally you can actually modify the query to give you the full CREATE INDEX statement, so you just need to copy that to a query window and execute it. The full query I usually use, looks like this: view source print? 01.DECLARE @DBName VARCHAR(100) 02.DECLARE @TableName VARCHAR(100) 03.--If this line is commented in, the missing index list will only contain 04.--missing indexes for the given database 05.--SET @DBName = 'MyDatabase' 06.--SET @TableName = 'MyTable' 07. 08.;WITH CTE 09.AS 10.( 11.SELECT 12. DB_NAME(d.database_id) AS DatabaseName, 13. user_seeks, 14. user_scans, 15. avg_total_user_cost, 16. avg_user_impact, 17. d.equality_columns, 18. d.inequality_columns, 19. d.included_columns, 20. 'USE ' + DB_NAME(d.database_id) + '; CREATE NONCLUSTERED INDEX IX_' + 21. replace(replace(replace(replace(isnull(equality_columns, '') + 22. isnull(inequality_columns, ''), ',', '_'), '[', ''),']', ''), ' ', '') + 23. CASE WHEN included_columns IS NOT NULL 24. THEN '_INC_' + replace(replace(replace(replace(included_columns, ',', '_'), '[', ''),']', ''), ' ', '') 25. ELSE '' END + ' ON ' + statement + ' (' + 26. CASE 27. WHEN equality_columns IS NOT NULL AND inequality_columns IS NOT NULL 28. THEN equality_columns + ', ' + inequality_columns 29. WHEN equality_columns IS NOT NULL AND inequality_columns IS NULL 30. THEN equality_columns 31. WHEN equality_columns IS NULL AND inequality_columns IS NOT NULL 32. THEN inequality_columns 33. END + ')' + 34. CASE WHEN included_columns IS NOT NULL THEN ' INCLUDE (' + 35. replace(replace(replace(included_columns, '[', ''),']', ''), ' ', '') + ')' 36. ELSE '' END + 37. CASE WHEN @@Version LIKE '%Enterprise%' THEN ' WITH (ONLINE = ON)' 38. ELSE '' END AS CreateIndex 39.FROM 40. sys.dm_db_missing_index_groups g 41. INNER JOIN sys.dm_db_missing_index_group_stats gs on gs.group_handle = g.index_group_handle 42. INNER JOIN sys.dm_db_missing_index_details d on g.index_handle = d.index_handle 43.WHERE 44. (DB_NAME(d.database_id) = @DBName 45. OR @DBName IS NULL) 46.) 47.SELECT * FROM CTE 48.WHERE CreateIndex LIKE '%'+@TableName+'%' OR @TableName IS NULL 49.ORDER BY user_seeks DESC Feel free to modify to match your naming standards.