copy database structure from sql server to other - sql-server

I want to copy a database to a sql server to another, but i just want to copy structure (views, stored procedures, tables, fields, indexes, etc), no rows.
I tried to generate a script from sql server management but the script is very verbose (task menu > create as)

Follow Below steps for generate script :
Right Click on Database
Select task
Select Generate Script from Task
Follow the steps
Finally finish for complete this process
You can either use the SQL Server Management Object API (see task "creating, altering and removing databases"):
C# Code for generate sql script :
public string GenerateScript()
{
var sb = new StringBuilder();
var srv= new Server(#"Your Database Server Name");
var db= server.Databases["Your Database name"];
var scrpt = new Scripter(srv);
scrpt.Options.ScriptDrops = false;
var obj= new Urn[1];
foreach (Table tbl in db.Tables)
{
obj[0] = tbl.Urn;
if (tbl.IsSystemObject == false)
{
StringCollection sc = scripter.Script(obj);
foreach (var st in sc)
{
sb.Append(st);
}
}
}
return sb.ToString();
}

You case use Copy database wizard
Some limitations of the it are :
1.The Copy Database Wizard is not available in the Express edition.
1.The Copy Database Wizard cannot be used to copy or move databases that:
Are System.
Are marked for replication.
Are marked Inaccessible, Loading, Offline, Recovering, Suspect, or in Emergency Mode.
Have data or log files stored in Microsoft Azure storage.

Related

nhibernate logs sql for postgres but not for sql server

I'm new to nhibernate (but used hibernate for java before).
I built a session factory for our sql server database (sql server enterprise edition 8)
ISessionFactory factory2 = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(#"user id=xx; password=xxx;server=xxx;initial catalog=xxx")
.ShowSql()
)
.Mappings(m => m.FluentMappings
.AddFromAssemblyOf<Program>())
.ExposeConfiguration(cfg => new SchemaValidator(cfg).Validate())
.BuildSessionFactory();
So I use the ShowSql() method to log the queries to the console.
In my programm I load / create two objects and want to persist them and then do a update on a column:
using (var session = sf.OpenSession())
{
session.FlushMode = FlushMode.Always;
using (var ta = session.BeginTransaction())
{
Console.ReadKey();
PMA pm = session.CreateCriteria<PMA>()
.Add(Restrictions.Eq("Name", "HANSER")).List<PMA>().FirstOrDefault();
if (pm == null)
{
pm = new PMA();
pm.Prio = "1";
pm.Name = "HANSER";
pm.Datum = DateTime.Now;
session.Save(pm);
}
Clip clip = new Clip();
clip.PMA = pm;
clip.sys_created = DateTime.Now;
clip.sys_name = "system name";
clip.Title = "Test";
session.Save(clip);
Console.ReadKey();
clip.Title = "PETERSEN";
session.SaveOrUpdate(clip);
session.Transaction.Commit();
session.Flush();
session.Dispose();
Console.ReadKey();
}
}
The first insert for the pm object will be logged on the console, but the other insert and the update for the clip object don't appear in the console. When I look in the database, I see there is everything right, everything will be inserted and updated. But I want to see the query. I try to set flush mode to always and make a session.Flush() to the session at the end and then a session.Dispose(), but nothing changes.
When I use postgres (only change the sessionfactory), I see all query logs.
How can I let nhibernate log all queries for sql server ?
When using ADO.NET batching (on by default in SQL Server, which supports it), DML queries are not logged to the console.

Memory Leak in SQL Server while using Linq to SQL

I am using the following pattern to update my SQL Server records using Linq to SQL:
List<int> allIds;
using (MyDataContext dc= new MyDataContext())
{
dc.CommandTimeout = 0;
allIds = dc.MyTables.Select(x => x.Id).ToList();
}
Parallel.ForEach(allIds, x => ComputeAndSave(x));
and
ComputeAndSave(int x, MyDataContext dc)
{
var myRecord= dc.MyTables.Select(x => x).Where(x => x.Id == id).FirstOrDefault();
myRecord.Total = myRecord.Total + 1; //some modification(s)
dc.SubmitChanges();
}
I use the same pattern in multiple parts of my application to update all rows in some tables. And in all these cases, memory used by SQL Server slowly increases and increases and increases. The only way I find to release all that memory is to stop and restart the SQL Server Service. Why is there a memory leak here and how can it be fixed?
Many thanks!
SQL Server is supposed to take all available memory. It is supposed to run on headless servers.
In SSMS, open the server properties and set a reasonable amount of max server memory.

Problems deleting data from database

I am using Hibernate to access my database. I would like to delete a set of fields on function of a criteria. My database is PostgreSQL and my Java code is:
public void deleteAttr(String parameter){
Configuration cfg = new Configuration();
cfg.configure(resource.getString("hibernate_config_file"));
SessionFactory sessionFactory = cfg.buildSessionFactory();
session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
tx.begin();
String sql = "delete from attribute where timestamp > to_date('"+parameter+"','YYYY-MM-DD')"
session.createSQLQuery(sql);
tx.commit();
}
The method runs, but it doesn't delete data from database. I have also checked the sql sentence in PgAdmin and it works, but not in code. Why? Does someone help me?
Thanks in advance!
It's because you're creating a query, but you don't execute it:
String sql = "delete from attribute where timestamp > to_date('"+parameter+"','YYYY-MM-DD')"
Query query = session.createSQLQuery(sql);
query.executeUpdate();
You should really use bound named parameters rather than string concatenation to pass parameters in your query: it's usually more efficient, it' much more robust, but above all, it doesn't open the door to SQL injection attacks.

How can I copy data records between two instances of an SQLServer database

I need to programmatically (ADO.Net) copy records from a table in one database to a table in another database on a different server.
This is very similar to "How can I copy data records between two instances of an SQLServer database" except that I am not allowed to create a link to the destination server so the accepted answer to that question won't work for me.
You can use the SqlBulkCopy class
The SqlBulkCopy class suggested by santiiii is very efficient but it creates a non-logged operation. I had to do this once but my target database participated in replication, so I needed the operation to be fully logged. What I essentially ended up doing was selecting a dataset from the source database .
Select * from SourceDatabaseTable where (some clause to get the right records)
Then creating an empty dataset from the destination table with this statement
Select * from DestinationDatabaseTable where 1<>1
Then I had two datasets. The first with the records I wanted to copy and the second that is empty. Next I just did a nested foreach loop to copy the records from one dataset to the other. Here is the Pseudocode for the core copy function:
foreach(datarow sourcedr in sourcetable)
{
datarow destdr = destdatatable.createrow();
foreach(datacolumn in sourcedatatable)
{
destdr[datacolumn]=Sourcedr[datacolum];
}
}
Lastly, I just used a data adapter to submit the changes on the destination database.
Here's how I did it. Thanks to the other respondants for the inspiration. The code that builds the mappings is not necessary if the schemas of the two tables are identical.
public void CopyTables(string sourceConnectionString, string destConnectionString)
{
string sql = "Select * From SourceTable";
using (SqlConnection sourceConn = new SqlConnection(sourceConnectionString))
using (SqlCommand sourceCmd = new SqlCommand(sql, sourceConn)) {
sourceConn.Open();
using (SqlDataReader reader = sourceCmd.ExecuteReader())
using (SqlBulkCopy copier = new SqlBulkCopy(destConnectionString)) {
copier.DestinationTableName = "DestinationTable";
copier.BulkCopyTimeout = 300;
DataTable schema = reader.GetSchemaTable();
copier.ColumnMappings.Clear();
foreach (DataRow row in schema.Rows) {
copier.ColumnMappings.Add(row["ColumnName"].ToString(), row["ColumnName"].ToString());
}
copier.WriteToServer(reader);
}
}
}
}

PowerBuilder DSN Creation

I am new to PowerBuilder.
I want to retrieve the data from MSAccess tables and update it to corresponding SQL tables. I am not able to create a permanent DSN for MSAccess because I have to select different MSAccess files with same table information. I can create a permanent DSN for SQL server.
Please help me to create DSN dynamically when selecting the MSAccess file and push all the tables data to SQL using PowerBuilder.
Also give the full PowerBuilder code to complete the problem if its possible.
In Access we strongly suggest not using DSNs at all as it is one less thing for someone to have to configure and one less thing for the users to screw up. Using DSN-Less Connections You should see if PowerBuilder has a similar option.
Create the DSN manually in the ODBC administrator
Locate the entry in the registry
Export the registry syntax into a .reg file
Read and edit the .reg file dynamically in PB
Write it back to the registry using PB's RegistrySet ( key, valuename, valuetype, value )
Once you've got your DSN set up, there are many options to push data from one database to the other.
You'll need two transaction objects in PB, each pointing to its own database. Then, you could use a Data Pipeline object to manage the actual data transfer.
You want to do the DSNLess connection referenced by Tony. I show an example of doing it at PBDJ and have a code sample over at Sybase's CodeXchange.
I am using this code, try it!
//// Profile access databases accdb format
SQLCA.DBMS = "OLE DB"
SQLCA.AutoCommit = False
SQLCA.DBParm = "PROVIDER='Microsoft.ACE.OLEDB.12.0',DATASOURCE='C:\databasename.accdb',DelimitIdentifier='No',CommitOnDisconnect='No'"
Connect using SQLCA;
If SQLCA.SQLCode = 0 Then
Open ( w_rsre_frame )
else
MessageBox ("Cannot Connect to Database", SQLCA.SQLErrText )
End If
or
//// Profile access databases mdb format
transaction aTrx
long resu
string database
database = "C:\databasename.mdb"
aTrx = create transaction
aTrx.DBMS = "OLE DB"
aTrx.AutoCommit = True
aTrx.DBParm = "PROVIDER='Microsoft.Jet.OLEDB.4.0',DATASOURCE='"+database+"',PBMaxBlobSize=100000,StaticBind='No',PBNoCatalog='YES'"
connect using aTrx ;
if atrx.sqldbcode = 0 then
messagebox("","Connection success to database")
else
messagebox("Error code: "+string(atrx.sqlcode),atrx.sqlerrtext+ " DB Code Error: "+string(atrx.sqldbcode))
end if
// do stuff...
destroy atrx

Resources