How To Programmatically Clone A Database?
Jan 21, 2005
Howdy,
Is the any easy way to clone a database programatically?
I've searched the web but did not come up with anything.
At the moment I create a new blank database (based on the model database)
and create tables, indexes, etc. via asp. (The databases are always exactly
the same)
It seems to me that it would be a better option to
create one database with tables, indexes, etc and copy
it to a new database (on the same server).
One of the options I'm considering would be to create a database,
fill it with tables and indexes, etc. and then detach it.
Whenever I need a new database all I would have to do is use the
file system object to copy and rename the mdf file and then reattach the
new mdf file.
I realise that I could also make the changes to the model
database so that all new databases have the same structure
but that would be my last resort.
Is there any easier way to do this? A stored procedure perhaps?
You're opinions and advice would be welcomed.
View 5 Replies
ADVERTISEMENT
Jan 19, 2007
How do I go about creating a cloned copy of an existing database on the same server? I basically want to set up a test copy of a production database, but let it reside on the same server with a slightly different name, prefixed with 'Testing_".
I typically just use Studio Express Manager and not scripts to do admin tasks. Here's what I tried that didn't work so well:
* Had full backups of production db
* Detached production database I wanted to clone
* From within Win Explorer, copy the .mdf and .ldf files within same data folder and gave them a new name, prefixing with "Testing_"
* Re-attached prodution db
* Attached "Testing_..." database
Sql Express seems confused at this point with new database I attached. It references the full path of the database I copied from (c:program filesmicrosoft sql servermssql.1data...". I rename the datbase, removing full path and prefixing with "Testing_".
* Using Sql authentication, changed the default database for the Login account to the new cloned copy of database.
* Did some query level data sanitizing to the cloned copy of the db. I am positive I performed this on the correct db.
* Was able to connect/authenticate to the cloned copy through a custom VB app on my dev machine, and all looked well.
* Tried to connect to the cloned db from another machine and couldn't. Went back to my dev machine and noticed the original production db looked hosed -- there were no tree nodes available to it! Was still able to connect to the cloned "Testing_" db copy, but not able to connect/authenticate anymore to the production copy.
* Detached cloned copy of "Testing_" db and moved it out of the data folder.
* Detached production db. Got an error msg indicating operation failure of some kind, but the database was gone from the tree.
* Reattached the production db but couldn't hit it from my custom vb app. Re-did the login and user accounts used by the app and was able to hit it. However, the data sanitizing I had done earlier in the cloned copy clearly was visibile in the production db!
* Had to restore production db from backup. Had problems authenticating from app, and recreated User account before the app was to connect.
Q1: What I am doing wrong? Sql Express was obviously as confused as me somewhere along the line.
Q2: Is specifying a default database used by a Login account necessary for a VB app like mine. I think it was something I discovered in the past, however, this would seemingly present a problem whenever I want my app to hit a different database, established through a connection string.
TIA...
Rick
View 10 Replies
View Related
Jul 23, 2005
HiI was in the situation of cloning a SQL server database last night.Today, a dependent application was behaving a little erratically thoughmost things were fine after sorting out some ntfs permissions. I'verecovered this database from backup exec before from a hot-backup, thisis the first time I've attempted this procedure though.Could I check with the experts here as to whether what I did was OK?Been googling to see if it is really the right thing to do, haven'tcome up with anything definitive...Assume server SOURCE and DEST:install DEST to same specification, OS, SQL patch level as SOURCE. Samepaths where applicable.shut down SQL server on bothCopy all datafile folder (d:sqldata) which is the full databaseincluding MASTER etc all over to DEST.Shut SOURCE down.Rename DEST to SOURCE, disable SQL server starting, set networksettings to those of SOURCE and reboot.Wait for things to settle after reboot and name change, bring SQLdatabase up.Client application now connects, I can't see any problems, but therehave been some strange anomalies in satellite applications today. Allhave been bounced to see if it's just a change they needed to notice,to no avail.Was that an OK operation to have done, or is there something just aboutto bite me when I'm not looking?Be grateful for any advice, I spent today pulling a lot of hair out.Thanks in advance :)AW
View 3 Replies
View Related
Apr 24, 2015
I have this requirement where some store procedures from a "seed" database need to be replicated to another database (on demand, so replication is not suppose to be use in this scenario).
I know it can be achieved by exporting the store procedures and then execute that at the B database but I want something a bit more automatic since it can be a large number of sprocs. I am trying something like this (still in dev):
SET NOCOUNT ON;
--
SELECT ROW_NUMBER() OVER(ORDER BY definition) seq, definition base
into #sprocs
FROM databaseA.[sys].[procedures] p
INNER JOIN databaseA.sys.sql_modules m ON p.object_id = m.object_id
[Code] ....
But I am sure there are way better ways to accomplish that...
View 4 Replies
View Related
Aug 6, 2015
I want to restore a database (from an encrypted .bak file) - but *not* over the live original if you take my meaning. Encryption is the standard AES-256 that comes with Sql Server 2014 btw. I don't want the original touched/altered in any way. I would like to capture a success message if possible.I can extract the physical device name of the database in question using the following code:
SELECT physical_device_name, *
FROM msdb.dbo.backupmediafamily
WHERE media_set_id =(SELECT TOP 1 media_set_id
FROM msdb.dbo.backupset
WHERE database_name='MyDatabase'
AND type='D'
ORDER BY backup_start_date DESC)
I would like if the newly restored database was rename to something different than 'MyDatabase' (as shown above) and has different logs than the original. If possible, and capture a success message when restored.
View 5 Replies
View Related
Sep 24, 2006
hellooI'm building an intranet accounting system, at the begining of each year the administrator must be able to create a new year DBfrom the applicationIs this possible knowing that im using SQL Server 2000, .net framework 1.1 Thank you in advanced
View 3 Replies
View Related
Sep 25, 2006
Helloo
Can I backup DB programatically, and then restore it with different name also programatically??
meaning:
I have db2006, can I backup this db then restore it as db2007 programatically???using a stored procedure for example????
So by doing this the user will be using db2007 @ the begininng of the year and so on each year
I'm using sql2000
Please I need your help
Thank you
View 4 Replies
View Related
Aug 30, 2006
I've seen several post asking for that possibility, but all 've read, didn't help me.Some sing SQLDMO, other suggest to use SQLSMO, others only explaining to connect to a server and then do "CREATE DATABASE".I will do this within .Net. Connecting to a SQL Server 2005 and execute "CREATE DATABASE" I could realize.But how doing this with SQLExpress? Trying to do SqlConnection.Open with a non existing DB does not work., says "file not exists".Or do I only have the wrong connection string? Can someone post here an excample connection string, which works with a non existing database?Some hints I've read make me considering to use SQLSMO. But I don't have it on my computer. Where do I get it from? Any links would be nice.
View 6 Replies
View Related
Apr 5, 2006
I recently had to find ways to programmatically backup and restore anSQL Server Express database.For backup, I found a one-liner stored procedure that does the job(BACKUP DATABASE Toy to disk = 'c:ProjectsToy.bak'.My question is, is there something as simple for a restore operation?Thanks in Advance-Kostas
View 4 Replies
View Related
Jan 23, 2008
VWD 2005 Express. Visual Basic. SQL Server 2005.
I know how to set up SqlDataSources and their insert, delete, update, and select commands. I also have code for querying a Sql table and populating a dataset and scanning the dataset for values. However, I do not know how to modify records in a Sql table programmatically. Here is what I need to do:
I need to open a Sql table.
I need to process record bny record to check a particular field for a particular value.
If the field has the particular value, I need to change it and write the record back to the table with the modification.
The table is named "SystemUser" and the field is call "SystemUserTypeId."
Can anyone provide me with sample code that would accomplish this? Thanks for the help.
View 5 Replies
View Related
May 2, 2008
hai
I need to copy an instance of SqlDataReader type. I perform a query and stores its details to an instance of SqlDataReader type. Now before i read it, i want to make a clone as i got to use it again just after sometime. I found something like ICloneable.Clone. But i couldnot find much on the internet as to how to use it. Can anybody give me a sample as to how to go about this
View 1 Replies
View Related
Aug 6, 2006
Not sure if there is anyway to do hots on sql server .From all I haveheard an EMC can do clones and fractures in order to implement a hotbackup or some kind of it in sql server.Seemingly the DBA has to do something toenable the fracture of the clone . Is anyone familiar with this ?Your input is highly appreciatedMB
View 1 Replies
View Related
Apr 20, 2015
I have a table in which I have defined 2 columns. First column is called 'name' and second is called 'number'.It looks like sample bellow:
Name | Number |
---------------------------------
John | 2 |
Jessica | 3 |
Jack | 2 |
etc...
I need to make a query that will have the following results:
Name |
----------
John |
John |
Jessica |
Jessica |
Jessica |
Jack |
Jack |
John for 2 rows, Jessica for three rows and Jack for two rows. Is it possible only with loops or is there in SQL a duplicate/clone function...?
View 3 Replies
View Related
Jan 3, 2008
Hi all
this is my code and i find it in microsoft's site
if i run it with sql server connection it works but if i try to use it with sql express it give me this error:
CREATE FILE encountered operating system error 5(access denied) while attempting to open or create the physical file 'c://mydatabase.mdf'
it seems as a permission error but it isn't. I have to set something in sql express while in sql server it is already setted?
static void WriteDB()
{
String str;
//sql server connection
SqlConnection myConn = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master");
//sql express connection
SqlConnection myConn = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\MyDatabaseData.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\MyDatabaseLog.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
thanks
Marco
View 3 Replies
View Related
May 12, 2008
I'm trying to compact a SQL CE database programmatically. I've copied the code from MSDN, and it's fine as far as it goes, but there's a problem tying to compact a database in a ClickOnce application because you don't know the path to the database. You have to use the "|DataDirectory|" in your connection string to signify the path to the database. But when I try the file operations to replace the old database with the compacted version, I get an error message that the path "|DataDirectory|" is not valid. Here's the code:
SqlCeEngine engine = new SqlCeEngine("Data Source = " + src + "; Password =" + txtPassword.Text);
try
{
engine.Compact("Data Source = " + dest + "; Password =" + txtPassword.Text);
ShowMsg("Compacting...", MsgType.NoError);
}
catch (Exception ex)
{
MessageBox.Show("There was an error completing the operation: " + ex.Message);
}
engine.Dispose();
File.Delete(src);
File.Move(dest, src);
(dest is = src + ".tmp", i.e., a path to a tmp file to hold the database while compacting).
How do I locate the files to copy if I can't use "|DataDirectory|"?
View 3 Replies
View Related
Mar 12, 2008
Hi Guys,
I was wondering if there is a system procedure / T-SQL code to programmatically Failover a Database from Principal to mirror mode?
also,
We noticed that at times few of all the databases that were kept on 'Principal' mode get randomly 'Failover'. Does anyone have any idea?
If so, pls respond.
Thank you.
View 9 Replies
View Related
Jun 28, 2006
When my app starts up I want to ensure that the database compatibility level has been set to 90. I know about sp_dbcmptlevel, but that only seems to work in an interactive session; the documentation says it can't be used in a stored procedure, and that appears to be true. Does anyone know how I could read the database compatibility level in a stored proc?
View 3 Replies
View Related
Apr 4, 2015
I have a table "t_prod_cat" which contains hierarchical data which is used in production to present data.
CREATE TABLE [dbo].[t_prod_cat](
[cat_node_id] [bigint] IDENTITY(1,1) NOT NULL,
[advertiser_id] [bigint] NOT NULL,
[cat_hid] [hierarchyid] NULL,
[level] AS ([cat_hid].[GetLevel]()) PERSISTED,
CONSTRAINT [PK_t_prod_cat] PRIMARY KEY CLUSTERED
(
[cat_node_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
In order not to impact the production website during the time an advertiser is editing (the editing might take much time and also mainly because at any time during the editing, the advertiser could cancel all the changes he did), I was thinking of transferring all the data linked to that advertiser to another table and let the advertiser apply any modifications up to the moment he will commit the changes.
Therefore, I would like to "CLONE" the hierarchy related to a certain advertiser_id to another table "t_prod_cat_work"
CREATE TABLE [dbo].[t_prod_cat_work](
[temp_cat_node_id] [bigint] NOT NULL,
[temp_cat_hid] [hierarchyid] NOT NULL,
[advertiser_id] [bigint] NOT NULL
) ON [PRIMARY]
What can be the easiest way to clone all the hierarchical data (multi-levels) from 't_prod_cat' to 't_prod_cat_work' for a certain advertiser_id ?
View 2 Replies
View Related
May 24, 2015
I am having three table tblTest,tblTestQuestion,tblAnswers
Each test can have multiple question and each Question can have multiple answers.
Now I am already having records in database. I wants to create clone copy of existing test except testdetails in tblTest because the test will be unique, and then insert questions and answers into their respective tables.
I was trying to create SP but stuck.
Please find below tables structure
[code="
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblAnswer](
[Code].....
View 5 Replies
View Related
Jul 10, 2012
I need to be able to create & connect to temporary databases programmatically, and NOT using the command-line, within a C# program. How would one go about doing this?
View 7 Replies
View Related
Sep 4, 2015
Ive successfully cloned an SSRS VM Server within a scale out deployment to REPLACE a current physical machine. This wasn't too difficult.
The issue im having now is in creating a new SQL 2014 Environment with 3 SSRS nodes. Ive taken the time to build one up. Changed all my config files, installed all components etc & tweaks needed within my company...
I have now hit a brick wall though. Ive cloned this first server twice to give me 3 nodes. This is a new environment so the issue I have is that the rsreportserver.config files all now have the same InstallationID. I dont have any existing nodes to overwrite these files with. So when I attach the nodes to the database they will update the keys table with the same InstallationID as the first node and none will work.
Any way to force the SSRS setup to re-generate an installation ID - by repair maybe? Or is this something I can manually just make up?
View 0 Replies
View Related
Mar 10, 2015
Recently we had multiple production failures because one database was in single-user mode. I am trying to recreate this scenario to write a script that will kick out that connection that was holding database in single-user.In SSMS window 1 I run the following code:
use master
go
alter database test
set single_user
with rollback immediate
[code]....
Yes, it shows one record, but the database name is master, not test. And indeed, I run it from the context of master. Also tried sp_who, sp_who2, sys.dm_exec_requests - nothing works. For dm_exec_requests it shows nothing because it does not run at the current moment.Any other solutions to catch this SPID with a script?
View 5 Replies
View Related
Apr 4, 2006
I need to programmatically backup a database in SQL Server Express. I actually also need to programmatically restore it from a backup file. How can I do this programmatically? I know how to do simple ADO commands for simple db operations, but backup and restore sound like "meta" commands to me, and I don't know where to begin from.
View 15 Replies
View Related
Apr 16, 2007
I'm building SSIS packages through code and I would like to set the properties of some custom tasks (not data flow tasks) to expressions. I've done some searches but turned up nothing. This is the only thing I'm hitting a brick wall on at the moment; Books Online has been excellent in detailing how to create packages via code up to this point.
For the sake of argument, let's say I want to set the SqlStatementSource property of an Execute SQL task to this value:
"INSERT INTO [SomeTable] VALUES (NEWID(), '" + @[User:omeStringVariable] + "')"
What would the code look like?
View 4 Replies
View Related
Jun 9, 2007
Ok. So I have this ASP.NET page and I've programmatically taken a report from the report server and rendered it in PDF. Now I would like to take this a step further and save the report as a pdf document on the local machine.
So at this point I have a byte array representing the document, now how would I save this as a pdf on the local machine? I'm unaware of an ASP Response method to allow this and I'm unaware of a SSRS ReportingService method, but as I said I'm unaware...
Any ideas, thoughts, resources are all welcome.
View 1 Replies
View Related
Sep 10, 2006
hi all... how can i change the collation of a table that i dynamically created during runtime??i wanna change the default collation to Arabic
View 2 Replies
View Related
Oct 27, 2006
Hi ,Can we make a backup from a SQL-server 2000 database programmatically, using asp.net and then restore this backup programmatically ?
View 4 Replies
View Related
Jan 10, 2007
Hi Guys, I have this SqlDataSource, that counts some records and sets it in "NotStartedBugs". How do I retrive "NotStartedBugs" programmatically?
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT (SELECT COUNT(*) AS Expr1 FROM tickets WHERE (TicketType = 'Bug') AND (TicketStatus = 'Not Started')) AS NotStartedBugs"></asp:SqlDataSource>
View 1 Replies
View Related
Feb 16, 2007
Hi,
I am using Visual Web Developer 2005 Express Edition.
I am trying to SELECT three information fields from a table when the Page_Load take place (so I select the info on the fly). The refering page, sends the spesific record id as "Articleid", that looks typically like this: "http://localhost:1424/BelaBela/accom_Contents.aspx?Articleid=2". I need to extract the "Article=2" so that I can access record 2 (in this example).
How do I define the SelectParameters or QueryStingField on the fly so that I can define the WHERE part of my query (see code below). If I remove the WHERE portion, then it works, but it seem to return the very last record in the database, and if I include it, then I get an error "Must declare the scalar variable @resortid". How do I programatically set it up so that @resortid contains the value that is associated with "Articleid"?
My code is below.
Thank you for your advise!
RegardsJan/*******************************************************************************
* RETRIEVE INFORMATION FROM DATABASE
*******************************************************************************/
// specify the data source
string connContStr = ConfigurationManager.ConnectionStrings["tourism_connect1"].ConnectionString;
SqlConnection myConn = new SqlConnection(connContStr);
// define the command query
String query = "SELECT resortid, TourismGrading, resortHits FROM Resorts WHERE ([resortid] = @resortid)";
SqlCommand myCommand = new SqlCommand(query, myConn);
// open the connection and instantiate a datareader
myConn.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
// loop thru the reader
while (myReader.Read())
{
Label5.Text = myReader.GetInt32(0).ToString();
Label6.Text = myReader.GetInt32(1).ToString();
Label7.Text = myReader.GetInt32(2).ToString();
}
// close the reader and the connection
myReader.Close();
myConn.Close();
View 3 Replies
View Related
Apr 17, 2007
Hello. Im trying to create an SQLDataSource control programmatically. I need to do this because I want to do some stuff on my MasterPage's 'Page_Init' event.
heres my code (Master.master.vb): Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
lblUser.Text = Page.User.Identity.Name
Dim PUser As New ControlParameter
PUser.ControlID = "lblUser"
PUser.Name = "LoginName"
PUser.PropertyName = "Text"
PUser.Type = TypeCode.String
PUser.DefaultValue = Page.User.Identity.Name
Dim SQLDS_Login As New SqlDataSource
SQLDS_Login.ID = "SQLDS_Login"
SQLDS_Login.ConnectionString = "I put conection string here. How do I use the one on my web.config?"
SQLDS_Login.SelectCommand = "SELECT [LoginID], [LoginName], [Role], [Status] FROM [myLogin] WHERE ([LoginName] = @LoginName)"
SQLDS_Login.SelectParameters.Add(PUser)
SQLDS_Login.SelectCommandType = SqlDataSourceCommandType.Text
GridView1.DataSource = SQLDS_Login
GridView1.DataBind()
End Sub
When i run, i get this error message:
The SqlDataSource control 'SQLDS_Login' does not have a naming container. Ensure that the control is added to the page before calling DataBind.
I never had any problem with Inserts, Updates and Deleting, but I have never made it work for Select when doing it programmatically.
Can you help me with this?
View 1 Replies
View Related
Jul 15, 2007
I am trying to add a number of dates into a Sql database. Basically I want the user to add the start and end date and then all the dates in between are are added to a database in unique records. I can create an ArrayList but I don't know how to bind it to an SqlDataSource Dim startdate As DateTime = tbstartdate.Text Dim enddate As DateTime = tbenddate.Text Dim datediff As TimeSpan = enddate.Subtract(startdate) Dim noofdays As Integer = datediff.Days Dim ar As New ArrayList Dim i For i = 0 To noofdays ar.Add(startdate.AddDays(i)) Next Sorry if this is a total noob question....
View 1 Replies
View Related
Feb 14, 2008
I am trying to customize my update statement and this MUST happen in codebehind, otherwise I will be overwriting data. The following is updating the data that is should be. The problem is that eventhough my UpdateCommand is clear in my .aspx and there are no parameters set... It is STILL running it's own update and overwriting the information it isn't supposed to. From what I can tell, it is using a default. What can I do to prevent this?
SqlDataSource1.UpdateCommand = "UPDATE MyTable SET MyField1=@MyField1 WHERE MyField2=@MyField2 AND MyField3=@MyField3"SqlDataSource1.UpdateParameters.Add("MyField1", "CustomText")
SqlDataSource1.UpdateParameters.Add("Task_ID", "Parameter")SqlDataSource1.UpdateParameters.Add("Comments", "Parameter")
SqlDataSource1.Update()
View 3 Replies
View Related
Apr 27, 2006
I have a GridView bound to a SqlDataSource. On page load I would like to programmatically specify a SelectParameter value based on the role of the user. This SelectParameter will be used in my WHERE clause. The closest post I can find is http://forums.asp.net/thread/1233258.aspx but no answer was posted.
What code would I use to modify a SelectParameters value? Is it possible to reference a parameter by name (SqlDataSource1.SelectParameters["usertype"]) or does it have to be by index? (SqlDataSource1.SelectParameters[0])
Alternatively, perhaps I'm going about this in the wrong way, is there a better way to have dynamic GridView content based on the role of the user?
Thank you very much for your help.
View 3 Replies
View Related