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.

T-SQL Programming

T-SQLProgrammingI purchased my copy back in 1999 and it is one of my favorite SQL books. I find the information very accurate and relevant to the MS SQL versions (6.5 & 7.0) printed on the cover of the book. I think it was the best SQL book for many years. Since 1999, many books for newer versions of database servers have been published.

For some reason, many people who wrote bad reviews about this book were looking for MS SQL 2000 information -the cover states the versions covered in the book.

There are many newer books that cover MS SQL 2000. One of my favorites is SQL Server 2000 Programming from Robert Vieira.

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.

Extreme Programming

Extreme Programming Pocket Guide by Shane WardenThis guide is very concise & straight to the point. Do not be fool by its size. Team and project managers along with business analysts should find this guide very useful. This pocket book is an easy read that packs enough meat to get you going with Extreme Programming. It is written for anyone who is interested on knowing about XP.

By the end of the book you’ll have a clear understanding of why use XP programming, practices, events, roles, code principles & style. Best of all, it provides you with clear examples and suggestions on how to adopt this methodology.

Cómo Escribir la Fecha en Español en MySQL

Aquí les presento una manera de generar la fecha en Español utilizando el resultado de la función DATE_FORMAT(myDate,’%M’) or DATE_FORMAT(myDate,’%W’).

January > Enero
February > Febrero
March > Marzo
etc etc

Monday > Lunes
Tuesday > Martes
Wednesday > Miércoles
etc etc
DELIMITER $$
DROP FUNCTION IF EXISTS fnFechaEnEspanol$$

CREATE FUNCTION fnFechaEnEspanol (valFecha datetime)
RETURNS varchar(36)

BEGIN
DECLARE valMes, valDia nvarchar(10);
DECLARE fEspanol nvarchar(36);

SELECT ELT(DATE_FORMAT(valFecha,'%'),'Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre')
INTO valMes;
SELECT ELT(DATE_FORMAT(valFecha,'%w'),'Domingo','Lunes','Martes','Miércoles','Jueves','Viernes','Sábado')
INTO valDia;

SET fEspanol = UPPER(CONCAT(valDia, ' ', valMes, ' ', DAYOFMONTH(valFecha), ' DE ', YEAR(valFecha), ' ', DATE_FORMAT(valFecha,'%r')));

RETURN fEspanol;
END$$

DELIMITER ;

 

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 /?

Cómo Insertar Registros de un Documento XML al Servidor SQL 2000 Utilizando el XML Bulk Load

Los registros de un documento XML pueden ser insertados fácilmente a una base de datos de MS SQL 2000 utilizando el objeto XML Bulk Load. El XML Bulk Load es parte del SQLXML Data Access Component y funciona de manera similar al BULK INSERT o la utilidad bcp. Es un objeto tipo COM que te permite insertar grandes cantidades de registros de modo rápido y eficiente.

Nota: Es preferible usar esta solución cuando el tamaño del documento XML es mayor de 5MB y se aplica al servidor SQL 2000 solamente. El servidor SQL 2005 tiene el XML Bulk Load incorporado y puedes ver ejemplos de cómo utilizarlo en la documentación del mismo.
Cabe destacar que el servidor SQL 2000 cuenta con la función OPENXML que facilita la manipulación de registros en un documento XML pero el uso de esta consume muchos recursos ya que el documento XML debe ser asignado a una variable. Más adelante veremos un ejemplo de cómo utilizar esta función.

Requerimientos
• SQLXML
• MS SQL 2000
• Conocimiento de XML
• El código fuente de este artículo

Empezamos por crear la tabla donde vamos a introducir los registros que aparecen en el documento XML. Este paso no es necesario como veremos más adelante en este artículo.

USE myBaseDeDatos;
GO
CREATE TABLE dbo.SalesOrderDetail (
SalesOrderID int NOT NULL ,
LineNumber tinyint NOT NULL ,
ProductID int NULL ,
SpecialOfferID int NULL ,
CarrierTrackingNumber nvarchar(25) NULL ,
OrderQty smallint NOT NULL ,
UnitPrice money NOT NULL ,
UnitPriceDiscount float NOT NULL,
ModifiedDate datetime NOT NULL,
rowguid uniqueidentifier NOT NULL,
LineTotal int NOT NULL);
GO

A seguir, crearemos el esquema XSD (click here)que describe el documento XML. En el primer elemento de este esquema podrás observar que hago referencia a la tabla “SalesOrderDetail”. Este elemento es utilizado para crear un vínculo entre el documento XML y la tabla donde se insertarán los registros si la tabla existe en la base de datos o en caso de que no exista, la tabla será creada con este nombre. Los elementos que siguen nombran las columnas de la tabla que existe o que se va a crear al igual que el tipo de data de las mismas.

Ya que tenemos el documento XML y el esquema XSD, procedemos a crear un pequeño programa en VBScript para ejecutar el único método del XML Bulk Load (Execute) el cual requiere de dos parámetros, el nombre del esquema (XSD) y el nombre del documento XML. Abre una sesión del Notepad y copia el texto que aparece en el Código3. Salva este archivo con el nombre BulkLoad.vbs en la misma carpeta donde tienes el documento XML y el XSD.

Option Explicit

Dim strMsg
Dim objBL
set objBL = CreateObject("SQLXMLBulkLoad.SQLXMLBulkload.3.0")
with objBL
.ConnectionString = "provider=SQLOLEDB;data source=localhost;database=dev;integrated security=SSPI"
.ErrorLogFile = "e:'error.log"
.SchemaGen = true
.Execute "Salesorderdetail.xsd", "Salesorderdetail.xml"
end with
set objBL=Nothing
strMsg = "Done!" & vbCrLf
msgbox(strMsg)

En el Código4 tenemos un procedimento almazenado que utiliza la función OPENXML y los procedimientos de systema sp_xml_preparedocument y sp_xml_removedocument para manipular un documento XML. Ahora, ya estamos listos para hacer nuestras pruebas y comparar el XML Bulk Load contra el OPENXML.

CREATE PROCEDURE dbo.prcINSERTSalesOrderDetail
       @strXML ntext

AS

SET NOCOUNT ON

DECLARE @iDoc int

EXEC @iDoc OUTPUT
   , @strXML

INSERT INTO dbo.SalesOrderDetail (
       SalesOrderID,
       LineNumber,
       ProductID,
       SpecialOfferID,
       CarrierTrackingNumber,
       OrderQty,
       UnitPrice,
       UnitPriceDiscount,
       ModifiedDate,
       rowguid,
       LineTotal)
(
SELECT *
  FROM OpenXML(@iDoc, '/table/row',2)
  WITH (SalesOrderID int,
        LineNumber tinyint,
        ProductID int,
        SpecialOfferID int,
        CarrierTrackingNumber nvarchar(25),
        OrderQty smallint,
        UnitPrice money,
        UnitPriceDiscount float,
        ModifiedDate varchar(30),
        rowguid varchar(60),
        LineTotal float)
)

EXEC sp_xml_removedocument @iDoc
GO

Ahora voy a describir los pasos que debes seguir para hacer las pruebas con el archivo ZIP que acompaña este artículo.
1. Descargar el archizo ZIP aqui.
2. Abrir una sesión del Analizador de consultas (Query Analyzer) y ejecutar el texto del archivo DataBaseObjects.sql
3. Ejecutar el 1_OPENXMLLoad.vbs. Inserta registros utilizando la función OPENXML.
4. Borrar todos los registros de la tabla SalesOrderDetail ejecutando el TRUNCATE TABLE SalesOrderDetail.
5. Ejecutar el 2_BulkLoad.vbs. Inserta registros utilizando el XML Bulk Upload.
6. Borrar todos los registros de la tabla SalesOrderDetail ejecutando el TRUNCATE TABLE SalesOrderDetail.
7. Ejecutar el 3_BulkLoad.vbs

En el paso 2, creamos la base de datos “dev”, la tabla “SalesOrderDetail” y el procedimiento almacenado “prcInsertCustomer”. En el paso 3 ejecutamos el 1_OPENXMLLoad.vbs el cual inserta los registros del documento salesorderdetail_OPENXML.xml a la tabla “SalesOrderDetail” la cual debe tener 67,599 registros. Después de remover los registros de la tabla “SalesOrderDetail” deben ejecutar el 2_BLoad.vbs el cual inserta los mismos 67,599 registros a la tabla “SalesOrd
erDetail” pero esta vez utilizando el XML Bulk Load. Es aquí donde podemos comparar la eficiencia y velocidad del XML Bulk Upload contra la función OPENXML. Además de ser más rápido, el XML Bulk Upload puede manejar documentos XML más grandes ya que estos no son cargados en la memoria. En el último paso, ejecutamos el 3_BulkLoad.vbs el cual inserta 121,371 registros de un documento XML de 60MB en menos tiempo y utilizando menos recursos de sistema que cuando ejecutamos el paso número tres.

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

RECURSOS: SQLXML 3.0