How To: List databases in a SQL Server using T-SQL and truncate their logs#

Finally i'm back after a month of crazyness due to my webhost not performing up to its promise of 99.9% uptime.

Enough with the rant and on with the article, today i'm going to talk about how to list databases in a SQL Server by just using T-SQL and then showing you how to truncate the logs on those databases in different ways.

First, let's look at the 5 different approaches that you can use to list down databases in SQL Server by just using plain old T-SQL.

The stored procedure approach ( sp_databases, sp_helpdb ) :

 
USE master;

-- Lists databases that either reside in an instance of the SQL Server 
-- 2005 Database Engine or are accessible through a database gateway.
EXEC sp_databases

-- Reports information about a specified database or all databases.
EXEC sp_helpdb

The sys tables approach ( sys.databases, sys.sysdatabases ):

USE master;

-- [SQL Server 2000/2005] Contains one row for each database in an instance of 
-- Microsoft SQL Server 2005. When SQL Server is first installed, sysdatabases 
-- contains entries for the master, model, msdb, and tempdb databases. 
SELECT NAME FROM sysdatabases

-- [SQL Server 2005] Contains one row per database in the instance of Microsoft SQL Server. 
SELECT NAME FROM sys.sysdatabases

The using the undocumented stored procedure sp_MsForEachDatabase approach

USE master;

-- Undocumented SQL Server stored procedure
EXEC sp_msForEachDB 'PRINT ''?''';

Simple huh? Now that we know how to list databases let's go back to the problem of truncating all of them in one query (in fact it's just one line!). Some people would suggest writing cursors that would loop thru all the rows returned by our sysdatabases query to do this task. Their solution might be similar to the one listed below:

[SOLUTION 1]

USE master;

DECLARE 
    DBNames CURSOR
FOR
    SELECT 
        NAME 
    FROM sysdatabases

OPEN DBNames

DECLARE @Name varchar(50)

FETCH NEXT FROM DBNames
INTO @Name

WHILE (@@FETCH_STATUS <> -1)
BEGIN

    DBCC SHRINKDATABASE( @Name , 0)

    FETCH NEXT FROM DBNames
    INTO @Name

END

CLOSE DBNames
DEALLOCATE DBNames

Others would suggest a more primitive approach which is building a simple query first that would list the names of the database appended with the DBCC SHRINKDATABASE command:

[SOLUTION 2]

USE master;

SELECT 
    'DBCC SHRINKDATABASE(' + NAME  + ', 0)'
FROM sysdatabases

Then they would change the output option of the query into "Results to Text", copy the result to a new query window and execute the query from there. Pretty primitive. Alot of steps. Same results.

My suggested solution is using the sp_MSForEachDatabase procedure in conjunction with the DBCC SHRINKDATABASE function. This would result into a 1 line query. Less code with less steps to do that creates the same results.

[MY RECOMMENDED SOLUTION]

USE master;

-- truncates all the logs of all database in the server
EXEC sp_msForEachDB 'DBCC SHRINKDATABASE( ''?'', 0)'

Simple and straight to the point.

I hope you learned something from our article today. You can also do this programmatically by using C# and VB.NET. I wrote two articles about that topic here and here. Interested in truncating tables using sp_MsForEachTable? You can checkout this post.

Thanks!

 

.NET | Fun Stuff | Rant | SQL
Tuesday, January 22, 2008 7:58:26 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

My webhost frustration#
I've been hosting with IPower for 3 years now and man i'm getting really really really really really frustrated with their hosting! 2 years ago I had the same experience with them and it drove me crazy to the point that I was already shouting at their technical support agent. Imagine hearing this words "we don't have any backup of your site" in a time when you are getting really mad. Intense huh? Eventually my site was restored because "they actually" have a backup system in place. But this week is a different story...
Friday, January 11, 2008 7:32:21 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

How To: Use Extension Methods In .NET#
One of the cool feature (if used correctly) added to .NET 3.x is Extension Methods which enables you to extend an specific type by adding your own methods to it. It's useful in cases where you want to extend a library that you dont have access to the source.
Saturday, January 05, 2008 12:42:16 AM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

Free E-Books about LINQ, ASP.NET AJAX and Silverlight 1.0 from Microsoft#

Just in case you are interested... Microsoft is giving away Free E-Books of 3 great books



Introducing Microsoft LINQ
by Paolo Pialorsi and Marco Russo

ISBN: 9780735623910

Introducing Microsoft ASP.NET AJAX
by Dino Esposito

ISBN: 9780735624139

Introducing Microsoft Silverlight 1.0
by Laurence Moroney

ISBN: 9780735625396

 

Get them here!

Friday, January 04, 2008 9:16:54 PM (GMT Standard Time, UTC+00:00) #    Comments [1]  | 

 

Another weird Google search#
I've seen weird searches before in my refferal logs but i've never seen someone do a search like this...
Thursday, January 03, 2008 11:39:25 PM (GMT Standard Time, UTC+00:00) #    Comments [2]  | 

 

How To: Convert a string to MD5 in .NET#

I was working on a .NET application that integrates with Gravatar today because I needed a quickway to fetch someone's photo based on their email address. One requirement when doing this type of integration with Gravatar is that the email should be encrypted into an MD5 hash. Luckily, .NET already has a library that can do this for me by just calling a few methods:

[C# Version]

public static string ToMD5(string stringToConvert)
{
   //create an instance of the MD5CryptoServiceProvider
   MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();

   //convert our string into byte array
   byte[] byteArray = Encoding.UTF8.GetBytes(stringToConvert);

   //get the hashed values created by our MD5CryptoServiceProvider
   byte[] hashedByteArray = md5Provider.ComputeHash(byteArray);

   //create a StringBuilder object
   StringBuilder stringBuilder = new StringBuilder();

   //loop to each each byte
   foreach (byte b in hashedByteArray)
   {
      //append it to our StringBuilder
      stringBuilder.Append(b.ToString("x2").ToLower());
   }

   //return the hashed value
   return stringBuilder.ToString();
}

[VB.NET Version]

Public Shared Function ToMD5(ByVal stringToConvert As String) As String 
   'create an instance of the MD5CryptoServiceProvider 
   Dim md5Provider As New MD5CryptoServiceProvider() 

   'convert our string into byte array 
   Dim byteArray As Byte() = Encoding.UTF8.GetBytes(stringToConvert) 

   'get the hashed values created by our MD5CryptoServiceProvider 
   Dim hashedByteArray As Byte() = md5Provider.ComputeHash(byteArray) 

   'create a StringBuilder object 
   Dim stringBuilder As New StringBuilder() 

   'loop to each each byte 
   For Each b As Byte In hashedByteArray 
      'append it to our StringBuilder 
      stringBuilder.Append(b.ToString("x2").ToLower()) 
   Next 

   'return the hashed value 
   Return stringBuilder.ToString()
End Function

Now all I need to do is get the result of my function and pass it to the avatar page in the Gravatar website and it should return me my Gravatar image.

[C# Version]

string gravatarUrl = "http://www.gravatar.com/avatar.php?gravatar_id";
string gravatarID = Utilities.Strings.ToMD5("keith.rull@gmail.com");
Image1.ImageUrl = String.Format("{0}={1}",gravatarUrl,gravatarID);

[VB.NET Version]

Dim gravatarUrl As String = "http://www.gravatar.com/avatar.php?gravatar_id"
Dim gravatarID As String = Utilities.Strings.ToMD5("keith.rull@gmail.com")
Image1.ImageUrl = [String].Format("{0}={1}", gravatarUrl, gravatarID)

http://www.gravatar.com/avatar.php?gravatar_id=d7ae6b890f16ad7541732e0f38adcbf2

Awesome!

Wednesday, December 26, 2007 7:26:04 PM (GMT Standard Time, UTC+00:00) #    Comments [1]  | 

 

Developer Celebrity Deathmatch: Scott Hanselman vs. Phil Haack#

Have you ever thought about doing a Celebrity Deathmatch for developers? Well CodeSqueeze has just started one and in its first edition they have put two of the most popular .NET bloggers face-to-face. Scott "The Man" Hanselman vs. Phil "You will get" Haack.

Scott Hansleman has been on the forefront of technology and blogging for many years. Before recently joining Microsoft, Scott is most famous for his blog Computer Zen, where he releases famed “Ultimate Tool” lists, and primary driving force behind the Das Blog project. His recent adventure is trying his hand at podcasting which can be found at Hanselminutes.

Phil Haack is most known for his blog Haacked. Rarely off-topic, he flexes his mature .NET development skills with in-depth examples and anecdotes. By day, he is a Sr. Program Manager at Microsoft - by night, he is the lead of Subtext an open source blog engine.

Checkout the blow by blow breakdown and see who is the winner of the first ever Celebrity Deathmatch for developers ;)

Friday, December 21, 2007 6:16:43 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

My LINQ Cheatsheet#

I've been banging .NET 3.5 lately and this rendezvouz with LINQ (Language Integrated Query) has been making my brain smile alot. I mean, how can you not like something so easy and well defined and makes your life as developer alot easier.

Anyhow, I just wanted to post my LINQ cheat sheet. It's not much and it's not even complete yet (I call this part 1.1). It consist of a few snippets that you might commonly do when doing LINQ processing. I'm planning to update this and hopefully I could find time this week to add some more piece of code that would demonstrate the other LINQ topics that I missed.

Anyway, here's some LINQ snippets:

//create our PersonService object
PersonService ps = new PersonService();

//get the list of person
PersonList listOfPerson = ps.GetPersonList();

//get a list of people with Gender set to Male
var maleOnlyList =
from l
in listOfPerson
where l.Gender == Gender.Male
select l;

//get a list of people with Gender set to female
//and declaring the returned fields
var femaleOnlyList =
from l
in listOfPerson
where l.Gender == Gender.Female
select new {
l.PersonID,
l.FirstName,
l.MiddleName,
l.LastName,
l.Email,
l.BirthDate,
l.Gender,
l.DateCreated };

//specify age
int selectedAge = 25;
//get a list of people with age greater than 25
var ageIsGreaterThan25 =
from l
in listOfPerson
where l.BirthDate >= DateTime.Now.AddYears(-selectedAge)
select l;

//get a list of people with a birthdate between a specified range
var birthdateBetweenRange =
from l
in listOfPerson
where
l.BirthDate >= DateTime.Parse("1/1/1980")
&& l.BirthDate <= DateTime.Parse("1/1/1981")
select l;


//order the result by lastname
var orderByLastNameSimple =
from l
in listOfPerson
orderby l.LastName
select l;

//order the list by birthdate and lastname
var orderByMultiple =
from l
in listOfPerson
orderby l.BirthDate descending, l.LastName ascending
select l;

//take three records
var takeThree = listOfPerson.Take(3);

//go to the 10th record and then take 3 records from there
var skipTenTakeThree = listOfPerson.Skip(10).Take(3);

//skip up until the Lastname is not equal to Thornton
var skipWhile = listOfPerson.SkipWhile(n => n.LastName != "Thornton");

P.S: There's more LINQ examples at the MSDN website.

 

Monday, December 17, 2007 8:36:31 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

NBA + SilverLight = Awesome#

Wow, NBA.com is now joining the silverlight bandwagon.

NEW YORK — Dec. 10, 2007 — The National Basketball Association (NBA) will employ Microsoft Silverlight on NBA.com to further enhance the online video experience for NBA fans around the world. Microsoft Silverlight, a cross-browser, multiplatform plug-in for delivering the next generation of media experiences and rich interactive applications for the Web, will also be utilized on WNBA.com and NBADevelopmentLeague.com.

NBA.com will feature a full-screen NBA photo gallery, offer video highlights and deliver additional interactive applications throughout the site using Microsoft Silverlight. Through the use of Microsoft Corp.’s new application, the NBA will be able to provide further access to its extensive digital video library, integrate the video experience seamlessly into the site, and ultimately provide fans with access to more online video features.

Read the full article here...

I'm a big NBA fan and i frequently visit the site (atleast 4 times a day). Basketball is one of the most popular sports in the world and this partnership I think would greatly boost the adoption of Silverlight in the mainstream.

One more reason why i should kick my gears up another notch with silverlight.

Wednesday, December 12, 2007 10:36:34 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

Surprising news of the day: Outsourcing pregnancies#
I saw this on MSN today...

Surrogate Mothers: Womb for Rent

Customer service, tech support...these days we outsource everything to India. So why not pregnancy? Here is a report on the growing number of Indian women willing to carry an American child.

Woah...
Tuesday, December 11, 2007 10:47:23 PM (GMT Standard Time, UTC+00:00) #    Comments [0]  | 

 

All content © 2010, Keith Rull
On this page
This site
Calendar
<January 2008>
SunMonTueWedThuFriSat
303112345
6789101112
13141516171819
20212223242526
272829303112
3456789
Archives
Sitemap
Blogroll OPML
Disclaimer

Powered by: newtelligence dasBlog 2.3.9074.18820

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts


Pick a theme: