Find All Queries Run Against a Table

This script will show you all the queries that have run against a particular table since the last time SQL Server was rebooted. This query is good in helping to define indexes. This only works against SQL 2008.

SELECT DISTINCT TOP 1000
	ProcedureName       = OBJECT_SCHEMA_NAME(qt.objectid) + '.' + OBJECT_NAME(qt.objectid)
	,SQLStatement		= SUBSTRING(
									qt.Text
									,(qs.statement_start_offset/2)+1
									,CASE qs.statement_end_offset
									WHEN -1 THEN DATALENGTH(qt.text)
									ELSE qs.statement_end_offset
									END - (qs.statement_start_offset/2) + 1
									)
	,DiskReads          = qs.total_physical_reads   -- The worst reads, disk reads
	,MemoryReads        = qs.total_logical_reads    --Logical Reads are memory reads
	,ExecutionCount     = qs.execution_count
	,CPUTime            = qs.total_worker_time
	,DiskWaitAndCPUTime = qs.total_elapsed_time
	,MemoryWrites       = qs.max_logical_writes
	,DateCached         = qs.creation_time
	,DatabaseName       = DB_Name(qt.dbid)
	,LastExecutionTime  = qs.last_execution_time
	--,sre.*
FROM sys.dm_exec_query_stats AS qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
CROSS APPLY sys.dm_sql_referenced_entities(
		OBJECT_SCHEMA_NAME(qt.objectid) + '.' + OBJECT_NAME(qt.objectid)
		, 'OBJECT'
	) sre
WHERE qt.dbid = db_id() -- Filter by current database
AND sre.referenced_schema_name + '.' + sre.referenced_entity_name = 'dbo.Table'
AND OBJECT_SCHEMA_NAME(qt.objectid) + '.' + OBJECT_NAME(qt.objectid)
VN:F [1.4.8_745]
Rating: 0.0/5 (0 votes cast)
Posted in DMV Queries, SQL Server 2008 | Leave a comment

Search Stored Procedure Text

To search within stored procedures, do the following:

SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE CHARINDEX('findme', ROUTINE_DEFINITION) > 0

Or you can use sysobjects:

SELECT *
FROM sysobjects so
JOIN syscomments sm
ON sm.id = so.id
WHERE CHARINDEX('findme', sm.text) > 0
VN:F [1.4.8_745]
Rating: 0.0/5 (0 votes cast)
Posted in SQL Server | Leave a comment

SQL Server 2005 vs SQL Server 2008

For anyone looking for any additional reasons to upgrade, this list may help:

Reasons To Upgrade (Worded For Management)

  1. Upgrading to 2008 will give an additional 3 years of support. So you’re looking at 7-8 years of support as opposed to 4-5 years on 2005. Source: founder of SQL Server Central. http://www.sqlservercentral.com/articles/Administration/3094/
  2. SQL 2005 SSIS – Buggy and has major shortcomings. Any enhancements for SSIS 2005 are halted.
    http://ayende.com/Blog/archive/2007/07/15/SSIS-15-Faults.aspx
    • Cannot create a global class in a project (i.e. - you have to re-write code everywhere)
    • CLR Framework is only a subset (Does not support External Assemblies or COM Interop)
    • DataTypes for transformations do not automatically map (have to manually be mapped using the mouse)
    • It is very hard to debug a package
    • Built-in logging displays tons of useless information and very little useful information
    • Difficult to find out specific information on the record-level about why an error occurred
    • Limited data types available in their flat-file connectors
    • Data flow tasks cannot include logical conditional flows like the process flows.
    • Script editors use VB.Net only (…my opinion)
    • Overall, just very sensitive and annoying.
  3. SSAS – Being a complete re-write, the 2005 Analysis services is less mature. Performance enhancements have been made in 2008. Personal experience has shown many errors when aggregating cubes and slower than expected on-the-fly aggregations than in SQL 2000 AS.
  4. Auditing – SQL 2008 implements auditing out of the box and functions asynchronously not hindering performance. Using SQL 2005 we will have to manually write auditing functionality or go third party. Depending on future auditing requirements, performance potentially can be impacted.
  5. Resource governor – SQL 2008 provides the ability to limit the resources of queries. This often happens with reporting procedures. Limiting the resources of non application centric resources will help end-user experience.
  6. Performance Data Collection - collect historical snapshots of system performance in a separate database
  7. Reporting Services – 2005 reporting services is very resource intensive and is not practical unless on a separate installation of SQL Server to perform report pagination/rendering. 2008 Reporting services is a rewrite of the reporting engine. http://www.microsoft.com/sqlserver/2008/en/us/wp-sql-2008-performance-scale.aspx
  8. Full text search – This is now integrated into the SQL Server engine and performance has been enhanced. http://www.microsoft.com/sqlserver/2008/en/us/wp-sql-2008-performance-scale.aspx
  9. Change Data Capture – For requirements to save or monitor historical information on changed data. Using SQL 2008 we can implement a non-invasive detection of changed records.
  10. CPU’s can be added on the fly
  11. Ability to compress data and use less disk space

Reasons For Developers

  • Change Data Capture (CDC) - very solid and great to use for determining changed records.
  • Additional enhancements made to minimal logging for inserts
  • Intellisense - Built in finally
  • Resource Governor - Very cool. Throttle the resources of users based on Memory or Processor
  • Declare and set a variables inline
  • New Grouping Sets allows analysis-like data in OLTP (Grouping Sets)
  • Table Valued Parameters - Pass a table into a stored procedure as a parameter
  • Merge Statement - No more upserts. Now you can perform update and insert operations in on statement. Great for updating historical tables
  • New DMV shows all object dependencies
  • Data compression - Compress tables at the row level or the page level. Saves a tremendous amount of space.
  • VN:F [1.4.8_745]
    Rating: 0.0/5 (0 votes cast)
    Posted in SQL Server 2008 | Leave a comment

    SQL Server Indexes Tutorial

    One of the important parts of SQL Server development and optimization is the creation of indexes. In order to create proper indexing strategies it is necessary to understand how indexes work. This tutorial will guide you step by step to fully understand indexes.

    There are only two different types of indexes. Clustered and NonClustered. There can only be one clustered index on a table and the reason is simple:

    • A Clustered index is the data of table sorted according to the columns you choose.
    • A NonClustered index is just like the index of a book. It contains data sorted so that it’s easy to find, then once found, it points back to the actual page that contains the data. (In other words, it points back to the clustered index)

    Suppose we are reading a book about biographical information of all the U.S. Presidents, and the book itself orders the biographies starting from the first president to the latest president. This ordering would represent the clustered index.

    Now suppose you asked two different people to find Franklin D. Roosevelt’s biography. One person was a historian and the other was an adolescent. The historian would quickly be able to find the presidents biography while the adolescent would have to scan through each page in order to find the biography. Even if the adolescent used the book’s index (akin to the non-clustered index), he would still have to search for the page after he found the page number.

    So it is always faster to find information off of the clustered index because the data in already at the “leaf-level” off the index.

    With this information, how do we determine what the clustered index should be? Well, it depends on the population of the people searching for the biographies. If it is mostly adolescents, then it would be more efficient to sort the book alphabetically rather than the historical order of the presidents.

    Now let’s say that 75% of the population are historians and the other 25% are the adolescents. The historians typically need a lot of different information regarding the president’s biographies, while all the adolescents need is the president’s age at the time they took office. In this scenario, it is more plausible to keep the ordering of the book (clustered index) based on the order of the president, then simply add the age of the president in the back index of the book (the non clustered index). That way the adolescents do not have to look into the front of the book (clustered index) for the president’s age. This would satisfy both requirements and would be efficient for both historians and adolescents.

    First let’s create our president’s table download and run: PresidentsTable

    After running, let’s turn on the execution plan (In SQL Server Managment Studio place your mouse in the query window and select Query -> Include Actual Execution Plan)

    Now execute the following query:

    SELECT
    	PresidentNumber
    	,President
    	,YearsInOffice
    	,YearFirstInaugurated
    FROM Presidents
    WHERE PresidentNumber = 32
    

    Now let’s view the execution plan:
    tablescanexecutionplan
    Without a clustered index, our book is in no particular order. To find president 32, we need to scan every page.

    Now let’s add a clustered index so we can organize our book according to PresidentNumber:

    CREATE UNIQUE CLUSTERED INDEX IDX_C_Presidents_PresidentNumber ON Presidents(PresidentNumber)
    

    And let’s run our query again:

    SELECT
    	PresidentNumber
    	,President
    	,YearsInOffice
    	,YearFirstInaugurated
    FROM Presidents
    WHERE PresidentNumber = 32
    

    tableseekexecutionplan
    Our execution plan now shows a “clustered index seek”. Meaning we did not have to look through every page of our book. We jumped right to page 32 and found the information on our president there.

    In summary, when we look up information based on the clustered index (the way the table is physically sorted), we naturally find all the information we are looking for already there (President, YearsInOffice, YearFirstInaugurated).

    Now, let’s create a non clustered index and look up the YearFirstInaugurated by president’s name:

    CREATE NONCLUSTERED INDEX IDX_NC_Presidents_President ON Presidents(President)
    

    Now let’s run our query to find the YearFirstInaugurated:

    -- Force our query to use the index
    -- (table is so small SQL Server bypasses it)
    SELECT
    	YearFirstInaugurated
    FROM Presidents WITH(INDEX(IDX_NC_Presidents_President))
    WHERE President = 'Franklin Roosevelt'
    

    If we look at our execution plan now, we will see that we initially looked the president’s name up in our index, then after finding the page where the presidents biography was located, we went to that page to grab the YearFirstInaugurated. This is denoted by the “Key Lookup”. (Also known as “Bookmark Lookup”)
    bookmarklookup
    This is a more expensive operation because our data is not at the “leaf-level” (or inline with the index we just searched), rather it is in the clustered index instead.

    So how do we fix this? In SQL Server 2005, a new feature was introduced called “included columns”. This allows us to include data at the leaf-level of an index. So rather than looking up YearFirstInaugurated in the clustered index, we can find it in the nonclustered index. Let’s drop our index and include YearFirstInagurated in our nonclustered index:

    DROP INDEX Presidents.IDX_NC_Presidents_President
    GO
    CREATE NONCLUSTERED INDEX IDX_NC_Presidents_President ON Presidents(President) INCLUDE(YearFirstInaugurated)
    

    And run our query one more time:

    -- Force our query to use the index
    -- (table is so small SQL Server bypasses it)
    SELECT
    	YearFirstInaugurated
    FROM Presidents WITH(INDEX(IDX_NC_Presidents_President))
    WHERE President = 'Franklin Roosevelt'
    

    Now we only have an index seek. Because as soon as we looked the president up in the index, we immediately also found the YearFirstInaugurated:
    indexseek

    VN:F [1.4.8_745]
    Rating: 0.0/5 (0 votes cast)
    Posted in Indexing | Leave a comment

    How You Know You’re a SQL Developer / DBA

    For those of you in the community that may be unaware of the signs of being a SQL DBA or developer, this may help to clarify:

    1. You use SSMS as a text editor.
    2. You despise programmers.
    3. Programmers despise you.
    4. You take offense to having to use a while loop.
    5. You’re tired of explaining why a business logic layer won’t work.
    6. You’re known as the asshole.
    7. You really are the asshole.
    8. When people IM you they think you are shouting at them.
    9. You think deadlines are for the powerless.
    10. You’re tempted to buy a terrabyte hard drive yourself so you don’t have to worry about disk space.
    11. You’ve considered backing up to a thumb drive at least once.
    12. Put my server on a VM?? Lol.. I don’t think so..
    13. With each slowdown you’re on a conference call with IT explaining how to open perfmon.
    14. No, standard edition is not an option
    15. You start work at 10 AM
    16. You leave work at 5 PM
    17. You take an hour and a half lunch
    18. Source Control?? Is that like a database backup?
    19. You spend 50% of the time doing analyst work
    20. Nope, reports still cannot be in real time
    21. You think maintenance windows means 12 - 1 pm.
    VN:F [1.4.8_745]
    Rating: 0.0/5 (0 votes cast)
    Posted in Ramblings | Leave a comment

    SQL Server Interview Questions

    The following interview questions have been used on multiple interviewees and seem to work out well in finding the different areas of expertise for an individual. The rating part at the beginning gives you an understanding of where the interviewer thinks they are at in the listed categories. You can then judge yourself after you ask the questions.

    1. On a scale of 1-10,
      rate yourself in the following categories:
      1. T-SQL
      2. Optimization
        (SQL Server Internals)
      3. Data Warehouse
      4. Database Administration
      5. Database Architecture
      6. Database slowdown
        troubleshooting

    T-SQL

    1. Name all the different kinds of Joins.
      1. OUTER
        JOIN – LEFT, RIGHT, CROSS, FULL
      2. INNER
        JOIN
    2. On a scale of 1 to 10, how important would you consider cursors or while loops for a transactional database?
      1. As close to zero as possible, mainly only used for maintenance or warehouse operations.
    3. What is a correlated sub query?
      1. When a sub query is tied to the outer query. Mostly used in self joins.
    4. What is faster, a correlated sub query or an inner join?
      1. Correlated
        sub query.
    5. What is faster, a correlated sub query or an exists?
      1. Exists
    6. What is the having clause and when is it used.
      1. Used to further filter a group by.
    7. What are the pros and cons of putting a scalar function in a queries select list or in the where clause?
      1. Trick question, mostly just cons. Scalar functions in these places make the query slow down dramatically.

    Internals

    1. Describe lock escalation
      1. A query first takes the lowest level lock possible with the smallest footprint
        (row-level). When too many rows are locked (requiring too much RAM) the lock is escalated to a range or page lock. If too many pages are locked, it may escalate to a table lock.
    2. What are the internal differences between #temp tables and @table variables
      1. SQL Server can create column statistics on #temp tables
      2. Indexes can be created on #temp tables
      3. @table variables are stored in memory up to a certain threshold.
    3. How does a clustered index differ from a non-clustered?
      1. Clustered index physically sorts the table data in that order.
      2. Non clustered index is a duplication of the data in the table with a pointer to the clustered index key.
    4. What are some of the join algorithms used when SQL Server joins tables.
      1. Loop Join (indexed keys unordered)
      2. Merge Join (indexed keys ordered)
      3. Hash Join (non-indexed keys)
    5. Name some possible warning signals you may see in an execution plan indicating the query
      is not optimized.
      1. Index Scan or Table Scan
      2. Hash Joins
      3. Thick arrows (indicating large work tables)
      4. Parallel streams (Parallelism)
      5. Bookmark lookup (or key lookup)
    6. What is a bookmark lookup? (Or key lookup)?
      1. When a non clustered index is used for the seek and the data needed was not
        at the leaf level.
    7. Which is faster a Table Scan, or a Clustered Index Scan?
      1. Trick question. Same speed.
    8. Describe recompilation. What causes it to happen and what are the differences between 2000 and 2005?
      1. When the cached execution plan for a query cannot be used so the procedure
        recompiles. It may happen because (1) underlying statistics change. (2) DDL changes within the procedure. (3) The parameters the procedure was compiled with vary from the recently passed in parameters. (4) The query plan was flushed from cache.

    Data Warehouse

    1. If moving a larger number of rows from one server to another using T-SQL with a linked-server,
      how would you limit the size of the batches so the transaction log does not fill up?
      1. Create a looping mechanism using SET ROWCOUNT and a while loop
      2. Use the new SQL 2005 GO statement to set batch sizes.
    2. In DTS or SSIS, name the three types of precedence constraints used in moving from one
      task to another.
      1. Success
      2. Failure
      3. Completion

    Slowdown Troubleshooting

    1. When there is a whole system slowdown that is verified to be the database, describe
      the steps you take to investigate it.
      1. Run sp_who2 and see if any blocking is taking place, or any queries are
        eating too much CPU or disk IO. Also check the # of connections.
      2. Locking.
      3. Log into the box, see if the box is slow. Check CPU, memory usage, page
        file usage.
      4. Open perfmon and check the page life expectancy and disk latency.
    2. If there are no physical indicators for the system slowdown, what is the first thing you should do?
      1. Update Statistics
    3. When one particular query is slow, describe the steps you take to investigate it.
      1. Run SQL profiler and determine if abnormal amounts of IO or CPU is used.
      2. Run profiler to determine if recompilation is a factor.
      3. Update the statistics.
      4. Check the execution plan.
    4. Name all the potential points of contention that can cause a database slowdown:
      1. CPU
        bottleneck
      2. Memory
        bottleneck
      3. Network
        IO bottleneck
      4. Disk
        IO bottleneck
      5. Paging
        File (process trimming)
      6. Lock
        contention
      7. Corrupt
        index
      8. Recompilation

    Database Administration

    1. What is the difference between a truncate and a delete and what is the minimum fixed-server role needed to truncate?
      1. Truncates are not logged and cannot be undone. Truncate requires dbo.
    2. What is the default number of worker threads in SQL 2000?
      1. 255
    3. What is parallelism?
      What is the default query threshold for parallelism?
      1. The optimizer decides to utilize multiple SPIDS running on different processors
        to query / transfer data. Default threshold is 5 seconds.
    4. Describe Log Shipping vs. Mirroring vs. Transactional Replication. What are the pros and cons?
      1. Log Shipping is asynchronous and sends transaction log file updates at a
        minimal interval of 2 minutes.
      2. Mirroring replicates the entire database and is synchronous. By default, it commits the data on both sides prior to releasing the transaction.
      3. Transactional replication is asynchronous and can isolate specific tables.
    5. How many transaction logs can you create?
      1. As many as you want.
    6. What is the optimal Disk configuration for a database server and what RAID configurations would you use?
      1. RAID
        1 for the OS / Applications
      2. RAID
        1 for the page file
      3. RAID
        10 for the Data file (possibly RAID 5 for few writes)
      4. RAID
        1 (or 10) for the transaction log
    7. What do the following commands do?
    8. DBCC SHOWCONTIG
      1. Shows fragmentation within tables / indexes
    9. DBCC FREEPROCCACHE
      1. Clears the procedure cache removing all execution plans, all procedures are
        recompiled.
    10. DBCC DBREINDEX
      1. Performs a complete reorganization of the index. (Intrusive process)
    11. DBCC DROPCLEANBUFFERS
      1. Drops
        all the data that was cached in memory.
    12. What is AWE and
      what are the requirements?
      1. Address Windowing Extensions – Allows SQL to utilize greater than 4 GB of RAM. When used with 32 bit Windows PAE (Physical Address Extension) needs to be turned on.

    Queries
    1) Write a query to return the firstname, lastname and the most recent OrderID for all customers. The orders table contains all the orders for each customerID and the Customers table contains the customer personal information. Each order in the Orders table has an OrderDate.
    Answer

    SELECT
    o.OrderID
    ,c.FirstName
    ,c.LastName
    FROM Orders o
    JOIN Customers c
    ON o.CustomerID = c.CustomerID
    WHERE OrderDate = (SELECT MAX(OrderDate)
    FROM Orders
    WHERE CustomerID = o.CustomerID
    

    OR

    SELECT
    c.FirstName,
    c.LastName,
    o.OrderNumber
    FROM Orders o
    JOIN
    (
    SELECT MAX(OrderDate) AS MaxOrderDate,
    custid
    FROM orders
    GROUP BY custid
    
    ) o_2
    ON o.custid = o_2.custid
    AND o.orderdate = o_2.MaxOrderDate
    JOIN customers c
    ON c.CustID = o.CustID
    

    2. If this was the only query on used for these two tables, how would you create the clustered indexes?
    Customers – CustomerID
    Orders – CustomerID, OrderDate

    VN:F [1.4.8_745]
    Rating: 0.0/5 (0 votes cast)
    Posted in SQL Server | Tagged | Leave a comment

    Remove Duplicate Rows

    The following code is useful to delete duplicate records. This is where a primary key comes in handy. Of course if you do not have one, you have to improvise. This example uses rownumber in order to create a pseudo primary key.

    The Checksum function creates a single number from all the fields, then groups on that number. Please note, though highly unlikely (about 1 in 2 billion chance) the checksum function can return the same value for different row values.

    
    SELECT
    	RowNum = ROW_NUMBER() OVER(order by entryid ASC)
    	,ChkSum = CHECKSUM(*)
    INTO #HoldDuplicates
    FROM dbo.Duplicate
    
    DELETE
    FROM #HoldDuplicates
    WHERE RowNum NOT IN(
    	SELECT MAX(RowNum)
    	FROM #HoldDuplicates
    	GROUP BY ChkSum
    )
    
    SELECT *
    FROM #HoldDuplicates
    
    VN:F [1.4.8_745]
    Rating: 0.0/5 (0 votes cast)
    Posted in SQL | Leave a comment

    Replace Invalid Characters

    Unfortunately I haven’t found a way to remove invalid characters without looping. If anyone knows a way please post.

    This script will remove invalid characters:

    --Leave only numbers
    WHILE PATINDEX('%[^0-9]%',@string) > 0
     BEGIN
    
        SET @pos = PATINDEX('%[^0-9]%',@string)
        SET @string = REPLACE(@string,SUBSTRING(@string,@pos,1),'')
    
     END
    
    --Leave only characters
    WHILE PATINDEX('%[^a-z]%',@string) > 0
     BEGIN
    
        SET @pos = PATINDEX('%[^0-9]%',@string)
        SET @string = REPLACE(@string,SUBSTRING(@string,@pos,1),'')
    
     END
    
    VN:F [1.4.8_745]
    Rating: 0.0/5 (0 votes cast)
    Posted in SQL | Tagged | 2 Comments

    Dynamic Change Data Capture Solution (CDC)

    Change Data Capture, CDC is a feature that is completely revolutionizing SQL Server in respects to data flow.  Previous to change data capture, triggers or high water marks needed to be used in order to perform delta transfers of data to data warehouses or disparate systems.

    This example shows the use of a custom CDC solution that utilizes a definition table which stored table and column names in order to create a meta-data driven CDC subscription.

    First create your CDC subscription table

    CREATE TABLE [dbo].[Columns_To_Monitor_Sto](
    	[ColumnID] [int] IDENTITY(1,1) NOT NULL,
    	[DatabaseName] [varchar](40) NULL,
    	[SchemaName] [varchar](20) NULL,
    	[TableName] [varchar](255) NULL,
    	[ColumnName] [varchar](255) NULL,
    	[Ordinal] [int] NULL,
    	[IsActive] [tinyint] NULL,
     )
    

    With the table now created, we have a meta data repository of columns. Anything added or removed from this table will automatically get added or removed from the CDC subscription.

            DECLARE @DebugMode int                                     = 1
    	DECLARE @source_schema varchar(20)
    	DECLARE @source_name varchar(255)
    	DECLARE @role_name varchar(20)				= 'cdc_manager'
    	DECLARE @supports_net_changes int			= 1
    	DECLARE @captured_column_list varchar(MAX)	= ''
    	DECLARE @TableCount int
    	DECLARE @iOrigCount int
    	DECLARE @capture_instance nvarchar(MAX)
    	DECLARE @TableName varchar(255)
    	DECLARE @IsCDCEnabled int
    
    	CREATE TABLE #TablesToMonitor
    	(
    		ID					int				IDENTITY(1,1)
    		,SchemaName			varchar(20)
    		,TableName			varchar(255)
    		,ColumnsToMonitor	varchar(MAX)
    		,CaptureInstance	varchar(MAX)
    		,IsCDCEnabled		bit
    	)	
    
    	INSERT INTO #TablesToMonitor
    	(
    		TableName
    		,SchemaName
    		,ColumnsToMonitor
    		,CaptureInstance
    		,IsCDCEnabled
    	)
    	SELECT DISTINCT
    		rcm.TableName
    		,rcm.SchemaName
    		,ColumnsToMonitor	= SUBSTRING((SELECT
    										',' + r.ColumnName
    										FROM(
    											SELECT DISTINCT TableName,ColumnName
    											FROM dbo.Columns_To_Monitor_Sto
    											WHERE IsActive = 1
    										) r
    										WHERE (r.TableName = rcm.TableName)
    										FOR XML PATH('')   ), 2, 8000)
    		,CaptureInstance	= rcm.SchemaName + '_' + rcm.TableName
    		,IsCDCEnabled		= (CASE WHEN ct.object_id IS NULL THEN 0 ELSE 1 END)
    	FROM dbo.Columns_To_Monitor_Sto rcm
    	LEFT JOIN cdc.change_tables ct
    	ON ct.capture_instance = rcm.SchemaName + '_' + rcm.TableName
    
    	IF @DebugMode = 1
    	BEGIN
    		SELECT * FROM #TablesToMonitor
    	END				
    
    	-- Count the number of tables to loop
    	SET @TableCount = (SELECT MAX(ID) FROM #TablesToMonitor)
    
    	IF @DebugMode = 1
    	BEGIN
    		SELECT @TableCount
    	END
    
    	WHILE @TableCount > 0
    	BEGIN
    
    		-- Populate Variables
    		SELECT
    			@source_schema			= tm.SchemaName
    			,@source_name			= tm.TableName
    			,@capture_instance		= tm.CaptureInstance
    			,@captured_column_list	= tm.ColumnsToMonitor
    		FROM #TablesToMonitor tm
    		WHERE tm.ID = @TableCount
    
    		BEGIN TRY
    			-- Disable the table
    			EXEC sys.sp_cdc_disable_table
    			@source_schema			= @source_schema --mandatory
    			,@source_name			= @source_name --mandatory
    			,@capture_instance		= @capture_instance;
    
    		END TRY
    		BEGIN CATCH
    			SELECT 'Disable CDC Failed', ERROR_MESSAGE(), @source_name
    		END CATCH
    
    		BEGIN TRY
    			-- Enable the table
    			EXEC sys.sp_cdc_enable_table
    			@source_schema			= @source_schema --mandatory
    			, @source_name			= @source_name --mandatory
    			, @role_name			= @role_name --mandatory
    			, @supports_net_changes = 1
    			, @captured_column_list = @captured_column_list
    			, @filegroup_name		= N'PRIMARY';
    
    		END TRY
    		BEGIN CATCH
    			SELECT 'Enable CDC Failed', ERROR_MESSAGE(), @source_name, @captured_column_list
    		END CATCH
    
    		SET @TableCount -= 1
    
    	END
    
    	UPDATE rcm
    	SET Ordinal = sys.fn_cdc_get_column_ordinal(SchemaName + '_' + TableName, ColumnName)
    	FROM dbo.Columns_To_Monitor_Sto rcm
    
    	IF @DebugMode = 1
    	BEGIN
    
    		select distinct tablename, columnname, 'not in CDC'
    		from dbo.Columns_To_Monitor_Sto
    		where IsActive = 1
    		AND columnname Not IN(
    		SELECT Column_Name
    		FROM cdc.captured_columns)
    
    		select column_name, 'not in Columns_To_Monitor'
    		from cdc.captured_columns
    		where column_name not in (
    		select distinct columnname
    		from dbo.Columns_To_Monitor_Sto
    		where IsActive = 1)
    	END
    
    VN:F [1.4.8_745]
    Rating: 0.0/5 (0 votes cast)
    Posted in SQL Server 2008 | Tagged , | Leave a comment

    SQL Server Keywords (Reserved Words)

    ADD EXCEPT PERCENT
    ALL EXEC PLAN
    ALTER EXECUTE PRECISION
    AND EXISTS PRIMARY
    ANY EXIT PRINT
    AS FETCH PROC
    ASC FILE PROCEDURE
    AUTHORIZATION FILLFACTOR PUBLIC
    BACKUP FOR RAISERROR
    BEGIN FOREIGN READ
    BETWEEN FREETEXT READTEXT
    BREAK FREETEXTTABLE RECONFIGURE
    BROWSE FROM REFERENCES
    BULK FULL REPLICATION
    BY FUNCTION RESTORE
    CASCADE GOTO RESTRICT
    CASE GRANT RETURN
    CHECK GROUP REVOKE
    CHECKPOINT HAVING RIGHT
    CLOSE HOLDLOCK ROLLBACK
    CLUSTERED IDENTITY ROWCOUNT
    COALESCE IDENTITY_INSERT ROWGUIDCOL
    COLLATE IDENTITYCOL RULE
    COLUMN IF SAVE
    COMMIT IN SCHEMA
    COMPUTE INDEX SELECT
    CONSTRAINT INNER SESSION_USER
    CONTAINS INSERT SET
    CONTAINSTABLE INTERSECT SETUSER
    CONTINUE INTO SHUTDOWN
    CONVERT IS SOME
    CREATE JOIN STATISTICS
    CROSS KEY SYSTEM_USER
    CURRENT KILL TABLE
    CURRENT_DATE LEFT TEXTSIZE
    CURRENT_TIME LIKE THEN
    CURRENT_TIMESTAMP LINENO TO
    CURRENT_USER LOAD TOP
    CURSOR NATIONAL TRAN
    DATABASE NOCHECK TRANSACTION
    DBCC NONCLUSTERED TRIGGER
    DEALLOCATE NOT TRUNCATE
    DECLARE NULL TSEQUAL
    DEFAULT NULLIF UNION
    DELETE OF UNIQUE
    DENY OFF UPDATE
    DESC OFFSETS UPDATETEXT
    DISK ON USE
    DISTINCT OPEN USER
    DISTRIBUTED OPENDATASOURCE VALUES
    DOUBLE OPENQUERY VARYING
    DROP OPENROWSET VIEW
    DUMMY OPENXML WAITFOR
    DUMP OPTION WHEN
    ELSE OR WHERE
    END ORDER WHILE
    ERRLVL OUTER WITH
    ESCAPE OVER WRITETEXT
    VN:F [1.4.8_745]
    Rating: 0.0/5 (0 votes cast)
    Posted in SQL | Tagged , | Leave a comment