Scripts útiles - Sql Server

Buenas! Continuando con el post anterior, hoy les dejo algunos scripts muy sencillos para Sql Server, pero que siempre vienen bien.

Son muy útiles. A mi me han servido.

Buscar un campo en una todas las tablas:

SELECT TABLE_NAME,*
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%NombreDeCampo%'


Buscar un Stored Procedure por algun fragmento del nombre:

SELECT ROUTINE_NAME, ROUTINE_DEFINITION, *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%palabraDelStored%'
AND ROUTINE_TYPE='PROCEDURE'


Buscar Stored Procedures por texto:

SELECT distinct

name SP_Name

FROM [sysobjects] INNER JOIN [syscomments] ON

[sysobjects].id = [syscomments].id

where xtype = 'P'

and text like '%textoabucar%'



Espero que les venga bien! Saludos!

Buscar FKs - Relaciones de Tablas - Sql Server

Hoy les dejo un post que les puede resultar muy útil.

A mi me ha sacado de más de un apuro.

Suele pasar que a veces trabajamos con bases de datos muy grandes, o que estén mal diseñadas o que simplemente no entendemos por completo su esquema. A mi me ha pasado en el trabajo con una base de datos diseñada fuera de Raona.

En trabajos como este necesitamos buscar información determinada, y nos pasamos recorriendo tablas y tablas.

Para evitar esto les dejo un script SQL, para SQL Server, para encontrar tablas con FKs que apuntan a una tabla que nosotros queramos. Este script nos devuelve la tabla donde se encuentra la clave foránea, la columna de la FK y además el nombre de la constraint.

-- RELACION DE TABLA (DEPENDENCIAS)

SELECT
FK_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
ConstraintName = C.CONSTRAINT_NAME
FROM
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK
ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK
ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN
(
SELECT
TC.TABLE_NAME, CU.COLUMN_NAME
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC
INNER JOIN
INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU
ON TC.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
WHERE TC.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT
ON PT.TABLE_NAME = PK.TABLE_NAME
WHERE
PK.TABLE_NAME = 'SALESORDERHEADER' -- TU TABLA



Espero sinceramente que le sirva a alguien!

ItextSharp - Escribiendo PDF en .Net

La semana pasada tuve que trabajar en una aplicación que generara un reporte en formato PDF, con datos obtenidos de una BBDD.

Es algo muy útil y práctico.

A continuación les dejo una explicación de cómo pueden generar archivos PDF desde .Net utilizando la biblioteca itextsharp que la pueden usar en forma gratuita.

Let's go!

Primero, añadimos a nuestro proyecto una referencia a esta biblioteca (este paso no lo voy a explicar ya que es muy sencillo, si alguien no sabe como hacerlo que me pregunte).

Ahora agregamos a nuestro código:

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;


namespace PDFApp
{
public class Query
{
public static XmlDocument ExecuteQuery(SqlCommand cmd, ref SqlTransaction trans)
{
if( cmd == null )
throw new ArgumentNullException("cmd", "El comando no puede ser null.");
if( trans == null )
throw new ArgumentNullException("trans", "La transaccion no puede ser null.");

XmlNode xmlrow = null;
XmlReader xmlreader = null;
XmlDocument xmldoc = null;
xmldoc = new XmlDocument();
xmldoc.LoadXml("");
xmlreader = cmd.ExecuteXmlReader();
xmlrow = xmldoc.ReadNode(xmlreader);
while ( xmlrow != null )
{
xmldoc.DocumentElement.AppendChild(xmlrow);
xmlrow = xmldoc.ReadNode(xmlreader);
}
xmlreader.Close();
return xmldoc;
}
public static XmlDocument ExecuteQuery(SqlCommand cmd, SqlConnection conn)
{
XmlDocument xmldoc = null;
SqlTransaction trans = null;
if ( conn != null )
{
if ( conn.State != ConnectionState.Open )
{
conn.Open();
}
cmd.Connection = conn;
}
else
{
throw new ArgumentNullException("cmd", "El comando no puede ser null.");
}
trans = cmd.Connection.BeginTransaction();
xmldoc = new XmlDocument();
xmldoc.LoadXml("");
try
{
cmd.Transaction = trans;
xmldoc = ExecuteQuery(cmd, ref trans);
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
throw ex;
}
return xmldoc;
}
}


Y ahora ponemos lo siguiente en el código del evento de un botón de nuestra página.

Document document = new Document(PageSize.A4, 90f, 50f, 90f, 60f);
try
{
XmlDocument Doc = new XmlDocument();
SqlConnection cnx = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=BASEDEDATOS;Data Source=SERVIDORSQL");

//Este es un ejemplo que toma datos de una tabla personas,
//Es muy importante poner "for xml raw !!!
SqlCommand cmd = new sqlcommand("select * from personas for xml raw");

cmd.Connection = cnx;
Doc = Query.ExecuteQuery(cmd, cnx);

// Configuración del documento PDF

string FullPathOut = "c:\\SalidaPDF.pdf";
PdfWriter.getInstance(document, new filestream(fullpathout, filemode.create));

// Fonts y colores

Font font_celdas = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL);
Font font_titulo_tabla = FontFactory.getFont(FontFactory.HELVETICA, 9, Font.BOLD,
new Color(255,255,255));
Color color_negro = new color(0, 0, 0);
document.Open();
Table table = new Table(3);
table.BorderWidth = 0;
table.BorderColor = color_negro;
table.Padding = 1;
table.Spacing = 1;
Cell titulo = new cell(new Phrase("Datos de la tabla", font_titulo_tabla));
titulo.Header = true ;
titulo.BackgroundColor = color_negro;
titulo.Colspan = 3;
table.addCell(titulo);
table.addCell(new Phrase("Nombre", font_celdas));
table.addCell(new Phrase("Num. Documento", font_celdas));
table.addCell(new Phrase("Teléfono", font_celdas));
table.endHeaders();
foreach(xmlelement elem in Doc.SelectNodes("/ROOT/row"))
{
table.addCell(new Phrase(Elem.GetAttribute("Columna1"), font_celdas));
table.addCell(new Phrase(Elem.GetAttribute("Columna2"), font_celdas));
table.addCell(new Phrase(Elem.GetAttribute("Columna3"), font_celdas));
}
document.Add(table);
}

catch (XmlException xex)
{
throw new Exception(xex.Message);
}
catch (DocumentException de)
{
throw new Exception(de.Message);
}
catch (IOException ioe)
{
throw new Exception(ioe.Message);
}
finally
{
document.Close();
}
}
}
}




Espero que les sirva! En la próxima continuaré con este tema!

Saludos!