Programmatically Attach/Detach SQL Server

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • RP

    #1

    Programmatically Attach/Detach SQL Server

    I am using SQL Server 2005 with C# 2005. I want to programmaticall y
    Detach a database, then copy its files from the data folder to another
    location and then Attach the database back. Can it be done using C# ?
    If yes, please illustrate.

  • Alberto Poblacion

    #2
    Re: Programmaticall y Attach/Detach SQL Server

    "RP" <rpk.general@gm ail.comwrote in message
    news:1190833056 .344756.171790@ r29g2000hsg.goo glegroups.com.. .
    >I am using SQL Server 2005 with C# 2005. I want to programmaticall y
    Detach a database, then copy its files from the data folder to another
    location and then Attach the database back. Can it be done using C# ?
    Yes, you can do that by openning a SqlConnection to another database
    (such as "master"), and sending a call to the system stored procedure
    sp_detach_db. You can do this by means of the method ExecuteNonQuery () of a
    SqlCommand object. Note that the detach will fail if the database is in use.
    After copying the database files (System.IO.File .Copy(...)), you
    reattach the database with a call to sp_attach_db, or better yet, CREATE
    DATABASE database_name FOR ATTACH.

    Comment

    Working...