Thursday, September 23, 2010

SQL Union

SELECT
Losstype as type,"LossType" as who,count(*) as counted
FROM
`losscodes`
group by losstype

union
select  "XXXX","DenialType",0
union
SELECT
DenialType as type,
"DenialType" as who,
count(*) as countit
FROM
denialcodes
group by denialtype
order by who,type


Produces:
<code>
Computers DenialType 2
Electronics DenialType 14
Furniture         DenialType 84
General         DenialType 12
XXXX         DenialType 0
                LossType 1
Appliance         LossType 1
Electronics LossType 11
Furniture         LossType 20
Lawn and Garden LossType 1
Pool and Spa LossType 1

</code>

Thursday, September 16, 2010

Getting Schema Information from your Database

by William Ryan
Print this ArticleDiscuss in Forums

There may be times when you'll want to interrogate your database and find information about it's schema like table names, table definitions etc.  ADO.NET gives us two very cool ways to accomplish this.  Most of the time, when you call one of SqlClient's methods or properties, you can do the same with OleDb, Odbc etc.  Most of the time, not always.  In this instance however, the approach is fundamentally different.  If you are using SqlClient, you simply query Sql Server's Information_Schema and restrict the results so that Table_Type = BASE TABLE.  On the other hand, with OleDb (Access comes to mind on this) you open a connection, and then call itsOleDbConnection.GetOleDbSchematable method.

So, assuming that you are using SqlClient, this is basically how you do it.
VB.NET
Dim cn as New SqlConnection("YourConnectionStringHere")
Dim da as New SqlDataAdapter("SELECT * FROM Information_Schema.Tables where Table_Type = 'BASE TABLE'", cn)
Dim dt as New DataTable
da.Fill(dt)

C#
SqlConnection cn = new SqlConnection("YourConnectionStringHere");
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Information_Schema.Tables where Table_Type = 'BASE TABLE'", cn");
DataTable dt = new DataTable();
da.Fill(dt);


However, if we do it with OleDb, we don't need a DataAdapter, we're going to let the connection get the information for us:
VB.NET
Dim cn as New OleDbConnection("YourConnectionStringHere")
Dim dt as New DataTable
cn.Open
dt  = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {nothing, nothing, nothing, "Table"})
cn.Close

C#
OleDbConnection cn = new OleDbConnection("YourConnectionStringHere");
cn.Open();
DataTable dt = new DataTable();
dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] {null, null, null, "Table"});
cn.Close


As you can see, there's not much to it.  Now, you're probably wondering what the whole New Object thing is about.  That is an array that you can pass in to restrict what comes back.  So, if you passed in values for the first element instead of nothing, only values that matched that value would be returned.  I don't use Access enough to really know what those other values are and I haven't been able to find out what other values you could pass in for "Table".  I'm guessing it will probably be indexes or views but that's purely conjecture on my part.  Regardless, if you want all of the information on all of the tables, the above code snippets will do it for you.  Also, remember that since we aren't using a DataAdapter object in the second part, we need to explicitly open and close the connections in order for it to work (It'd probably be pretty hard for a connection to return information about a database that it's never opened up to).

See Also, OleDbConnection.GetOleDbSchemaTable | OleDbSchemaGuid System.Data.OleDb |OleDbConnection Members

OledbSchema using C# and .net

Description :
At times, in addition to querying and updating data in a database, you also need to retrieve information about the database as well as its contents. This information is called Database Metadata. In this article, I will describe the ways to retrieve the database schema information using System.Data.SqlClient class and the System.Data.OleDb class.
The database schema also known as metadata, is how the database defines itself. By using the database schema information, you can see the database structure and all the data in it. When working with databases in .NET, you either use the System.Data.SqlClient class or the System.Data.OleDb class. These two classes retrieve the table schema differently. We will explore both the ways.
The OleDbConnection object exposes a GetOleDbSchemaTable method that you can use to retrieve schema information for your database, such as a list of tables or columns. GetOleDbSchemaTable returns a DataTable that is populated with the schema information. There is no direct equivalent to this feature in the SQL Client .NET Data Provider. The SQL Server .NET Data Provider exposes backend schema information through stored procedures and informational views. You simply query Sql Server's Information_Schema and restrict the results to Table_Type = 'BASE TABLE' or Table_Type = 'VIEW'. However do remember that for information schema views, the metadata returned is limited to that which the user has permission to view.
You can execute the following piece of code to retrieve information regarding the various tables on your SQL Server database:
SqlConnection cn = newSqlConnection("PutYourConnectionStringOverHere");
SqlDataAdapter da = 
new SqlDataAdapter("SELECT * FROM Information_Schema.Tables where Table_Type = 'BASE TABLE'", cn");
DataTable dt = 
new DataTable();
da.Fill(dt);

Using OleDbConnection.GetOleDbSchemaTable Method
When we retrieve schema information with OleDb, we don't need a DataAdapter. We're going to let the connection object get the information for us. The GetOleDbSchemaTable method returns schema information from a data source as indicated by a Guid.( A GUID represents a globally unique identifier (GUID). This identifier has a low probability of being duplicated as it is composed of a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required.) You supply a value from the OleDbSchemaGuid enumeration to specify the type of schema information you want, such as tables, columns, and procedures. In addition to taking the Guid schema argument, you can further restrict the results of the GetOleDbSchemaTable( ) through the second argument. This argument is an object array specifying column restrictions. Using the restrictions parameter, you can retrieve information for just a few selected columns in a particular table rather than retrieving information for all columns in your database. The syntax for the method is :
public DataTable GetOleDbSchemaTable(Guid schId, object[] restrictions)
Each value in the Object array corresponds to a DataColumn in the resulting DataTable. The Restrictions array for the member should have the following structure:
      {TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE}
When you pass values in the restriction array, include the 'null' keyword for array elements that do not contain values.
For E.g.: You can use the following code to retrieve just the columns from the Customers table:
string strConn = "Provider=SQLOLEDB;Data Source= server;" +
"Initial Catalog=Northwind;Trusted_Connection=Yes;";
OleDbConnection con = 
new OleDbConnection(strConn);
con.Open();
object[] objArrRestrict;
objArrRestrict = 
new object[] {nullnull,"Customers", null};
DataTable tbl;
tbl = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, objArrRestrict);

Retrieving a list of tables using the OleDbSchemaGuid
Since Information views are limited to SQL Server and won't work with other data sources, we have seen that the OleDbConnection object provides a GetOleDbSchemaTable() method that can return various types of schema information, similar to what SQL Server accomplishes with its built-in informational views. Each data source handles this task differently, depending on the data source, but the ADO.NET code is generic. Lets see an example
con.Open();object[] objArrRestrict;//select just TABLE in the Object array of restrictions.//Remove TABLE and insert Null to see tables, views, and other objects.objArrRestrict = new object[] {nullnullnull, "TABLE"};
DataTable schemaTbl;
schemaTbl = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,objArrRestrict);
// Display the table name from each row in the schemaforeach (DataRow row in schemaTbl.Rows)
{
listBox.Items.Add(row["TABLE_NAME"]);
Retrieving a List of Columns in a Table
The following code lists the names of columns in the Customers table in the SQL Server Northwind database.
OleDbSchemaGuid.Columns returns those columns in tables and views that are accessible to a given log on. If you specify an Object array of {null, null, "Customers", null}, you filter to include only the columns for the Customers table. Lets see the code :
con.Open();object[] objArrRestrict;
objArrRestrict = 
new object[] {nullnull, "Customers", null};
DataTable schemaCols;
schemaCols = con.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, objArrRestrict);
//List the schema info for the selected tableforeach (DataRow row in schemaCols.Rows)
{
listBox.Items.Add(row["COLUMN_NAME"]);
}

Summary:
In this article, we saw how to retrieve schema information using the GetOleDbSchemaTable and Visual C#. We also saw how the SQL Server .NET Data Provider exposes backend schema information through informational views. For listing tables in Access Databases, we have two techniques. The first technique uses the GetOLEDBSchemaTable( ) method to return schema information. For the second technique you'll need a reference to the Primary Interop Assembly for ADO provided in the file ADODB.DLL that uses ActiveX Database Objects Extensions(ADOX) from COM interop. ADOX has a Tables property that exposes a collection of Table objects in the database. I would recommend O'Reilly-ADO.NET CookBook to learn more about this.

How To Retrieve Schema Information by Using GetOleDbSchemaTable and Visual Basic .NET

http://support.microsoft.com/kb/309488