Wednesday, March 17, 2010

how to query duplicate records in SQL

SELECT *
FROM Person.Address A
INNER JOIN (SELECT AddressLine1, City
FROM Person.[Address]
GROUP BY AddressLine1, City
HAVING COUNT(*) > 1) AS A1
ON A.AddressLine1 = A1.AddressLine1
AND A.City = A1.City
ORDER BY A.AddressLine1, A.City, A.AddressID

Monday, March 1, 2010

how to get a list of tables in a database using C#

Unsurprisingly, if a table doesn't exist in a database, you can't use a select query to determine whether it exists. But using GetSchema() with no parameters, you can obtain a schema table, which is essentially a list of tables you can specify to get more specific schema information. In this case, I wanted to get a list of tables in the database. After transforming the results into a list of strings, I could then safely search the list to determine whether it exists.


SqlConnection con =
new SqlConnection("connection_string");
con.Open();
DataTable tbl =
con.GetSchema("Tables");


Schema and metadata retrieval using ADO.NET

this also works, depending on whether you need these extra parameters, but its a big uglier:


DataTable tables =
con.GetOleDbSchemaTable
(OleDbSchemaGuid.Tables,
new object[]{null,null,null,"TABLE"});


Get all table names