How to Script Database Tables with PowerShell

PROBLEM: I need an easy way to script out all the tables from a database in MS SQL 2000 and above.

SOLUTION: Like anything in programming, there are a thousand ways to skin a cat. Here, I’ll show you the simplest way I found to meet this request.

Go ahead and open a new session of PowerShell. You can type or copy and paste in your PS session window all the code in this solution. We will start by loading the SMO assembly.

[system.reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")|out-null

Next, we’ll create an instance of SMO server object, database object, and scripter object

$srv = new-object "Microsoft.SqlServer.Management.SMO.Server" "."
$db = new-object("Microsoft.SqlServer.Management.SMO.Database")
$scr = new-object("Microsoft.SqlServer.Management.SMO.Scripter")

We then assign the instance of MS SQL Server we want the scripter to use. We wrap it up by calling the Script() method with an SQL SMO collection of objects to be script out –in this case, all tables.

$scr.Server = $srv
$scr.Script($srv.Databases["AdventureWorks"].tables)

That’s it! The simplest way to script out all tables from a database with PowerShell. In a future article, I’ll expand from this solution by writing a script that will take parameters, use SMO Scripter Options, filter tables to be script out, and then some.

MCITP SQL Server 2005

MCITP Self-Paced Training Kit (Exams 70-431, 70-443, 70-444)I recommend The MCITP SQL Server 2005 Database Administrator Core Requirements book set to anyone preparing for the certification. These books provided me with invaluable knowledge & helped me pass all three exams on the first try.

I started my certification by reading The SQL Server 2005 Implementation and Maintenance. I also utilized a Transcender preparation exam. For the 70-431 I did not use the test included with the books. It took me 2 1/2 half days to read the book & take over and over the Transcender preparation exam.

I then continued with exam 70-443 by reading the Designing a Database Server Infrastructure Using SQL Server 2005. I read the book for 1 ½ day and took the practice exams included with the books at least 8 times. Even though I feel the preparation for this exam was easier, the exam itself was the hardest.

The final one, Optimizing and Maintaining a Database Administration Solution Using SQL Server 2005 took me 1 ½ days to prepare for; same as the 70-443. It was the longest exam of the three & I feel it was the easiest. I believe it was because the order, in which I took the exams, made it so much attainable given that the information of the previous test was always part of the subsequent ones.

70-229 Exam Cram

MCAD/MCSE/MCDBA 70-229 Exam Cram 2 by Thomas MooreIf you have several years experience with MS SQL 2000 you may be able to pass the 70-229 with this book only. A great way to measure your readiness is by taking the test that comes included in the CD. If you pass it with an 85 or above, I’ll say you’re ready. If you don’t, this book should be enough to prepare you for the test.

I also discovered that this book is a compressed regurgitation of the “MCSE SQL Server 2000 Database Design and Implementation Training Guide” (ISBN 0789729970) written by the same author a few years earlier. I definitely recommend the Exam Cram 2 instead of the one mentioned in this paragraph.

One thing I found very interesting is that the questions in the CD are extremely similar to the ones in the actual test. It will definitely give you a good sense of what the test is going to be like. Make sure you pass 3 practice tests with 85 or above before you go and take the real test.

Good luck!

SQL Server 2000 Programming

Professional SQL Server 2000 Programming by Robert VieiraBy far, this is the best overall MS SQL 2000 server book written until today. Most topics are covered from basic to advance level. This book is a must have for anyone who is looking to get a well rounded knowledge of what’s possible with MS SQL 2000.

The chapters I liked the most are:
Ch9 SQL Server Storage and Index Structures
Ch10 Views
Ch12 Stored Procedures
Ch15 Triggers
Ch16 Advanced Queries
Ch26 Full-Text Search
Ch29 Performance Tuning
All Appendixes

Noticed that I said “best overall” & “Most topics”; this book will not have an answer for very advance topics in areas like DTS, performance tuning, XML, & Analysis Services. There are great books out there if what you are looking for is not in Professional SQL Server 2000 Programming. The “Professional SQL Server 2000 DTS” is the best I have read when it comes to Data Transformation Services. For performance tuning and XML you may find books written by Ken Henderson to be among the best. For Analysis Services I have not found one book I will recommend yet.

Cómo Mover el Archivo LOG De Una Base de Datos

Algunas veces he tenido la necesidad de mover los archivos LOG de la base de datos de un disco duro a otro. En este artículo, voy a describir el código T-SQL que utilizo para lograr este objetivo.

Primero selecciono la base de datos y ejecuto el procedimiento de systema SP_HELPFILE para obtener el nombre y PATH donde se encuentran los archivos de la base de datos.

USE NorthWind
GO
SET NOCOUNT ON
EXEC SP_HELPFILE

En mi ordenador estan en C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDATA. Cambio la base de datos a master y separo la base de datos NorthWind

USE master
GO

EXEC SP_DETACH_DB 'NorthWind'
GO

Ahora abro una sesión de Windows Explorer para mover el archivo LOG a su nueva localidad. En mi ordenador lo copio a D:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDATA y regreso a mi sesión de analizador de consultas (Query Analyzer) para ejecutar el procedimiento de systema SP_ATTACH_DB y asi pegar la base de datos utilizando el nuevo PATH donde se encuentran los archivos de la base de datos

EXEC SP_ATTACH_DB 'NorthWind'
'C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDATANorthWind_Data.mdf',
'D:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDATANorthWind_Log.ldf'
GO

Cambio la base de datos nuevamente y ejecuto el procedimiento de systema SP_HELPFILE para verificar que la base de datos esta utilizando el archivo LOG en su nueva localidad. Tambien ejecuto el procedimiento de systema SP_HELPDB para verificar que la base de datos esta en linea.

USE NorthWind
GO
EXEC SP_HELPFILE
GO
EXEC SP_HELPDB 'NorthWind'
GO

Updated on 04/18/2011

El procedimiento almacenado sp_attach_db va a ser descontinuado en versiones proximas del SQL Server. Se recomienda que utilize el CREATE DATABASE database_name FOR ATTACH.

USE master
GO

CREATE DATABASE [NorthWind]
    ON (FILENAME = N'C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDATANorthWind_Data.mdf'),
       (FILENAME = N'D:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDATANorthWind_Log.ldf')
   FOR ATTACH
GO

Espero que encuentren ese pequeño artículo de ayuda.

Cómo Generar Una Secuencia de Comandos Para Transferir el Esquema de Una Base de Datos.

El poder generar una secuencia de comandos (Script) para generar todos los objetos de una base de datos es una función necesaria para cualquier administrador. Puedes salvar estos Scripts para comparar las diferentes versiones o para una migración de la base de datos a otro ordenador. La utilidad SCPTXFR te permite generar esta secuencia de comandos para crear el esquema de tu base de datos y guardarlo en uno o varios archivos.

Puedes utilizar el Administrador Corporativo (Enterprise Manager – EM) para crear un Script de tu base de datos. También puedes copiar tu base de datos de manera predefinida utilizando los Servicios de Transformación de Datos (DTS). Pero si lo que necesitas es crear un Script con el esquema de tu base de datos, el SCPTXFR puede ser tu solución.

La utilidad SCPTXFR se encuentra bajo el directorio C:’Program Files’Microsoft SQL Server’MSSQL’Upgrade del MS SQL Server 7.0 y el MS SQL Server 2000. Esta utilidad fue creada con el propósito de migrar base de datos del MS SQL 6.5 al MS SQL 7.0.

Para ver la lista de opciones y parámetros de esta utilidad puedes ejecutar el comando SCPTXFR /? Dentro de la carpeta donde se encuentra el archivo de esta utilidad. En mi ordenador se encuentra en
C:’Program Files’Microsoft SQL Server’MSSQL’Upgrade

SCPTXFR /s {server} /d {database} {[/I] | [/P {password}]}
{[/F {script files directory}] | [/f {single script file}]}
/q /r /O /T /A /E /C /N /X /H /G /Y /?

Buena Idea Mal Implementada

Una de las razones por la cual decidí escribir este artículo es porque alguien me sugirió utilizar el procedimiento de sistema SP_DEPENDS para encontrar las tablas que se usan en un SP (procedimiento almacenado). Al iniciar mis pruebas con el SP_DEPENDS utilizando la base de datos AdventureWorks todo parecía andar muy bien, pero cuando lo utilicé en una base de datos que ha estado funcionando por varios años, descubrí algunas fallas en él.

La idea principal del procedimiento SP_DEPENDS y la tabla de sistema SYSDEPENDS es la de tener un mecanismo que permita guardar información de la dependencia entre los objetos de la base de datos. Por ejemplo, si tenemos TABLA A, TABLA B y un SP C que haga referencia a ambas tablas mediante una consulta SELECT, podríamos ejecutar el SP_DEPENDS pasando el nombre de cualquiera de los tres objetos y veríamos que A esta relacionado a C, B esta relacionado a C y que C esta relacionado a A y B. Ahora bien, si ejecutamos el comando DROP TABLE A y luego recreamos la TABLA A, lo lógico seria que si ejecutamos el SP_DEPENDS nuevamente deberíamos obtener el mismo resultado que vimos anteriormente –pero no es así.

La falla esta en que cuando ejecutamos el comando DROP , todos los registros relacionados con el objeto que estamos eliminando se borran del SYSDEPENDS y aunque volvamos a crear el mismo objeto, las relaciones no se crean nuevamente. Volvamos al ejemplo anterior para explicarlo más detalladamente. Si se ejecuta un DROP TABLE A, entonces todos los registros en la tabla SYSDEPENDS de la TABLA A se borran y la dependencia A > C se desaparece. Al ejecutar el SP_DEPENDS con el objeto C como parámetro podremos observar que la unica relacion que existe es con la TABLA B aunque se aya creado la TABLA A nuevamente.

Así que bien, manténganse alejados del uso del SP_DEPENDS y SYSDEPENDS por ahora. Yo estaré haciendo pruebas con el servidor SQL 2005 a ver si Microsoft se tomó el tiempo y arregló este problema.

Puedes descargar el código aquí y no te olvides de añadir tus comentarios.

RECURSOS: –The Guru’s Guide to Transact-SQL
Transact-SQL Programming

The Object Within

Finding tables referenced in a stored procedure

Recently, I was asked for an easy way to list the tables used in a stored procedure. I looked in my list of previously used scripts and found one that did not fully satisfy the requirements of the task. So I decided to come up with a solution that will accurately list all tables referenced in a stored procedure. The solution is pretty straight forward and I’ll describe some of the 12 steps in the code that helped me find all referenced tables within it.

Overview of the problem
Sometimes it is necessary to know which tables are referenced or used in a stored procedure. If the stored procedure you’re working with, is one of those mega procedures of thousands of lines of code, it will be very tedious to go through line by line to find all tables referenced within the procedure.

While developing this solution, I encountered some issues rooted in the fact that stored procedures may be written in many different ways, especially the areas that make reference to tables. For example, take a look at the code in List 1 and see three ways you may write the same query.

There were so many variables that made the development of this solution very interesting. The sample code in List 1 reveals only the SELECT statement with three possible ways I would find reference to tables in stored procedures. Take into consideration that we need to account for the UPDATE, INSERT, and DELETE statements and all the different ways we may find them in the body of stored procedures.

SELECT a.Col1
       b.Col2
  FROM Table1 a,
       Table2 b
 WHERE a.ID = b.ID
SELECT a.Col1,
       b.Col2
  FROM Table1 a, Table2 b
 WHERE a.ID = b.ID
SELECT a.Col1,
       b.Col2
  FROM Table1 a
 INNER JOIN Table2 b ON a.ID = b.ID

First, I created two temporary tables. Table one (dbo.#Tables) will hold the name of tables and views from the database and table two (dbo.#Procedure) will hold the text from the stored procedure. Later in the script, I’ll verify the list of possible table names and view names found in the stored procedure (dbo.#Procedure) against the values in the first table (dbo.#Tables)to validate possible matches with the real object names.

Table one is populated with data from the SYSOBJECTS table WHERE type IN(‘U’,’V’). Notice in List 2 how I convert the data extracted from sysname data type to varchar to avoid any data comparison problems later in the code. I also made sure to TRIM the values from the SYSOBJECTS table.

INSERT dbo.#Tables(TableName)
SELECT CONVERT(VARCHAR(35), LTRIM(RTRIM(Name)))
  FROM dbo.SYSOBJECTS
 WHERE Type IN ('U','V')

You may need to check the maximum object name length in your SYSOBECTS table and update the table definition for dbo.#Tables and the CONVERT statement in List 2 in case the value of 35 is not long enough.

I used the SP_HELPTEXT extended procedure to populate table two. This process will insert one record per line of code returned by the extended procedure.

The following steps will modify the values stored in table two. I replaced any tabs, line feeds, and carriage returns with two spaces which will enable me to use the CHARINDEX() function later on in the solution. I also removed any rows with comments, temporary objects and the CREATE PROCEDURE statement since none of these rows should have the table names I’m looking for. I then looked for the first reference to a real table and removed all rows previous to this row.

The code in List 3 shows how I marked any rows with possible table names by setting the "PossibleTable" column to 1 and then removed all rows with NULL value in the same column.

SELECT @PossibleTable = Texto
  FROM dbo.Procedure
 WHERE Texto LIKE '%,%' AND
       Texto NOT LIKE '%(%';

IF @PossibleTable IS NOT NULL
   BEGIN
   INSERT dbo.#Procedure (PossibleTable, Texto)
   SELECT 1 AS PossibleTable,
          TableNames
     FROM dbo.fnParseCommaDelimitedList (@PossibleTable);
END

The UDF (User Defined Function) in List 4 is used on those rows that may have multiple table names separated by commas. The UDF takes one single parameter of up to 255 characters long and returns a table. It basically inserts one row in the return table for each value separated by a comma from the input parameter.

CREATE FUNCTION dbo.fnParseCommaDelimitedList (
       @myString VARCHAR (255))

RETURNS

@TableNames TABLE (
            TableNames VARCHAR (255))

AS

BEGIN

DECLARE @myPosition AS INT, 
        @myLen AS INT, 
        @myStart AS INT;

SELECT @myPosition = -1,
       @myString = @myString + ',',
       @myLen = LEN(@myString),
       @myStart = 1;

WHILE @myPosition < @myLen
      BEGIN

      INSERT @TableNames
      SELECT SUBSTRING(@myString, @myStart, CHARINDEX(',', @myString, 
                                 @myPosition + 1) - @myStart);

      SELECT @myPosition = CHARINDEX(',', @myString, @myPosition + 1);

      SELECT @myStart = @myPosition;
END
RETURN;
END

Conclusion
I have tested this solution against many stored procedures written in many different ways and I have found one condition that will cause some problems. It is on how you write your stored procedures and the width of your lines of code. You’ll need to increase the length of the "Texto" column in the dbo.#Procedure table If there are lines of code in your procedure longer than 255 characters. Make sure you have the necessary user rights to create the objects for this solution.

Download the code 01042006.sql and feel free to post your comments about this solution.

RESOURCES: BOL (MS SQL Books Online)

Generate T-SQL Script for a List of Views

USE:

CLEAR 

$sSRCServer = "TUIRA"
$sSRCDatabase = "AdventureWorks"

$oSO = New-SqlScriptingOptions
$oSO.Permissions = $true
$oSO.IncludeIfNotExists = $true

$a = Get-Content "C:tempviewlist.txt"

foreach ($o in $a) {
	Get-SqlDatabase $sSRCServer $sSRCDatabase|Get-SqlView -Name $o| `
                     Get-SqlScripter -scriptingOptions $oSO
	WRITE("GO `n`n`n")
}

 

Top 25 Most Expensive Stored Procedures

USE: These queries will display the top 25 most expensive stored procedures that are still in the cache.

SET NOCOUNT ON

--[ REVIEW MOST EXPENSIVE TOP 25 CACHED STORED PROCEDURES ]
--[ LOGICAL READS RELATE TO MEMORY PRESSURE               ]
SELECT TOP(25) A.name [SP Name]
     , B.total_logical_reads [TotalLogicalReads]
     , B.total_logical_reads / B.execution_count [AvgerageLogicalReads]
     , B.execution_count
     , ISNULL(B.execution_count / DATEDIFF(SECOND, B.cached_time, GETDATE()), 0) [Calls/Second]
     , B.total_elapsed_time
     , B.total_elapsed_time / B.execution_count [AverageElapsedTime]
     , B.cached_time
  FROM sys.procedures A
 INNER JOIN sys.dm_exec_procedure_stats B ON A.[object_id] = B.[object_id]
 WHERE B.database_id = DB_ID()
 ORDER BY B.total_logical_reads DESC;
 
 
 
--[ REVIEW MOST EXPENSIVE TOP 25 CACHED STORED PROCEDURES ]
--[ PHYSICAL READS RELATE TO IO PRESSURE                  ]
SELECT TOP(25) A.name [SP Name]
     , B.total_physical_reads [TotalphysicalReads]
     , B.total_physical_reads / B.execution_count [AvgeragePhysicalReads]
     , B.execution_count
     , ISNULL(B.execution_count / DATEDIFF(SECOND, B.cached_time, GETDATE()), 0) [Calls/Second]
     , B.total_elapsed_time
     , B.total_elapsed_time / B.execution_count [AvgerageElapsedTime]
     , B.cached_time
  FROM sys.procedures A
 INNER JOIN sys.dm_exec_procedure_stats B ON A.[object_id] = B.[object_id]
 WHERE B.database_id = DB_ID()
 ORDER BY B.total_physical_reads DESC;