Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  Data Programming  »  SQL Server  »  An introduction to SQL Server Management Objects  »  Enumerating and managing databases
An introduction to SQL Server Management Objects
by David Jeavons | Published  01/02/2007 | SQL Server | Rating:
Enumerating and managing databases

Now that we know how to connect to an instance of SQL Server we will probably want to do something useful. To start with, we may want to know what databases exist on the SQL Server we are connected to. To do this, we can enumerate the database collection of the Server object that we used when connecting to the SQL Server instance:

    1         For Each db As Database In sqlServer.Databases

    2             databasesListBox.Items.Add(db.Name)

    3         Next

 

The above code snippet adds the name of each database to a list box. I recommend that you spend some time looking at the various properties and methods of the database object as there are a number of things that you can ascertain about each database and operations that you can perform. For example, you can query the owner and size of the database by looking at the Owner and Size properties respectively and you can shrink a database by calling the Shrink method.

 

Creating new databases and attaching existing databases

 

To create a database you need to create a new Database object and call it’s Create method:


 

    1         Dim newDatabase As New Database(sqlServer, "MyNewDatabase")

    2         newDatabase.Create()

 

Note that the constructor for the Database object requires that you pass the server object that is currently connected to the instance of the SQL Server and the name of the new database.

 

If you want to specify the owner of the database then you can do this once the database has been created by calling the SetOwner method and passing the name of the owner:

 

    1         newDatabase.SetOwner("OwnerName")

 

To attach an existing database file to the connected instance of SQL Server then you can use the AttachDatabase method of the Server object:

 

    1         Dim files As New Collections.Specialized.StringCollection

    2         files.Add("PathToDatabase.mdf")

    3         sqlServer.AttachDatabase("MyNewDatabase", files)


Dropping and detaching existing databases

 

To drop an existing database you call the Drop method of the Database object that you wish to delete:

 

    1        sqlServer.Databases("MyNewDatabase").Drop()

 

Alternatively, you can detach a database by calling the DetachDatabase method:

 

    1         sqlServer.DetachDatabase("MyNewDatabase", False)

 

The DetachDatabase method has a couple of overloads allowing you to specify whether statistics for the database are updated and also to specify whether the full text index file should be removed or not prior to the database being detached.

Comments    Submit Comment

Comment #1  (Posted by an unknown user on 03/21/2007)
Rating
coz i dont be run the sample
 
Comment #2  (Posted by an unknown user on 03/23/2007)
Rating
You've got me going with SMO. Nice article.
 
Comment #3  (Posted by an unknown user on 03/23/2007)
Rating
You've got me going with SMO. Nice article.
 
Comment #4  (Posted by Jose on 05/31/2007)
Rating
How would I get a connection string with a specified database as the Initial Catalog?
 
Comment #5  (Posted by David Jeavons on 05/31/2007)
Rating
Hi Jose

I'm not quite sure I understand what you mean, but if you simply want to connect to a particular SQL Server instance then set the ServerInstance property of the ConnectionContext object to the name of the SQL Server of interest.

To automatically use a single database, you can declare a database object and assign it a value from the Databases collection of the Server object. So for example, assuming I was already connected to the SQL Server and I wanted to work with a database called "TestDB" directly then the could would be similar too:

Dim db As Database = Server.Databases("TestDB")

If this is not what you meant, could you clarify your question a bit.


HTH
 
Comment #6  (Posted by paul on 06/11/2007)
Rating
I Get the following error when i try to create stored procedure

BC30057: Too many arguments to 'Public Sub New()'.

at this line

Dim sp As New StoredProcedure , "MyNewStoredProcedure")

 
Comment #7  (Posted by David Jeavons on 06/11/2007)
Rating
The syntax for creating a stored procedure is similar too:

Dim db As Database = sqlServer.Databases("DBName")
Dim sp As New StoredProcedure(db, "sp_Name")

sp.TextMode = False
sp.TextBody = "SELECT FieldList FROM Table"
sp.Create()

Basically, you reference the database where you want to create the stored procedure and then when instantiating a new stored procedure object you specify the database that it will be related to and the name for the new stored procedure.


HTH
 
Comment #8  (Posted by paul on 06/11/2007)
Rating
I get the same error when i tryed to create a new store dprocedure on button click event

error : Compiler Error Message: BC30057: Too many arguments to 'Public Sub New()'.

my click even code is given below :

Dim sqlServer As New Server()
Dim db As Database = sqlServer.Databases("sample")
Dim sp As New StoredProcedure(db, "TestSmo")
sp.TextMode = False
sp.TextBody = "select state_name from state"
sp.Create()

ALL MY SMO COMMAND WORKES EXCEPT STORED PROCEDURE , KINDLY GET ME OUT OF THIS ERROR

 
Comment #9  (Posted by David Jeavons on 06/12/2007)
Rating
Hi Paul

The majority of your code should work as expected, however, I noticed that you are declaring a new server object and then using it immediately to grab a reference to the database of interest. You should in fact first create a connection to the server and then use that connection to create your reference to the database and create the procedure.

The above code example demonstrates connecting to the SQL Server instance of interest and once you have that you should then be able to utilise the code that you have to create the procedure.


HTH
 
Comment #10  (Posted by paul on 06/12/2007)
Rating
Hi David
I'm not able to correct the error till now just go through this code and please correct the lines where i make mistake

Dim connectionstring As String
connectionstring = "Data Source=.;Initial Catalog=sample;Integrated Security=True;Pooling=False"
Dim connection As New SqlConnection(connectionstring)
Dim sqlServer As New Server()
connection.Open()
Dim Server = New ServerConnection(connection)
Dim db As Database = sqlServer.Databases("sample")
Dim sp As New StoredProcedure(db, "testproc")
sp.TextMode = False
sp.TextBody = "SELECT * FROM state"
sp.Create()
Thanks and Regards
 
Comment #11  (Posted by David Jeavons on 06/13/2007)
Rating
Hi Paul

Try the following:

Dim sqlServer As New Server("ServerName")
sqlServer.ConnectionContext.Connect()

Dim db As Database = sqlServer.Databases("sample")
Dim sp As New StoredProcedure(db, "testproc")
sp.TextMode = False
sp.TextBody = "SELECT * FROM State"
sp.Create()

sqlServer.ConnectionContext.Disconnect()


HTH
 
Comment #12  (Posted by paul on 06/13/2007)
Rating
Hi david
still i get error on the line

Dim sp As New StoredProcedure(db, "testproc")

error : Too many arguments to 'Public Sub New()'.

i got a code written in c# which workes fine if possible tell me where lies the problem in vb code


c# code i used

string connectionString = "data source=.;initial catalog=sample;timeout=200;user id=sample; pwd=sample123;";
SqlConnection connection = new SqlConnection(connectionString);
Server server = new Server(new ServerConnection(connection));

Database db = server.Databases["sample"];

StoredProcedure SP = new StoredProcedure(db, "GetstateID");
SP.TextMode = false;
SP.AnsiNullsStatus = false;
SP.QuotedIdentifierStatus = false;

StoredProcedureParameter idParam = new StoredProcedureParameter(SP, "@ID", DataType.Int);
SP.Parameters.Add(idParam);

SP.TextBody = "Select * from state WHERE [ID] = @ID";

SP.Create();

thanks and regards
 
Comment #13  (Posted by paul on 06/28/2007)
Rating
Hi
is there a way to display the records inside the table i.e i would like to use a select statement on a particular table
 
Comment #14  (Posted by an unknown user on 01/03/2008)
Rating
Hi
Is there a way to export and import data from one server to another using SMO ? If so please post the syntax and procedure
 
Sponsored Links