Script table as CREATE TO by using vb.net - sql

In SQL server I can create a table which is duplicate of another table with all constraints set in it. I can use script table as CREATE TO in SQL server management studio to do this. Then I can run the script in another database so that same table is recreated but without data. I want to do same by using vb.net code. Important point is that all the constraints and table properties are set properly.

You can use the SMO (SQL Server Management Objects) assembly to script out tables to a string inside your application. I'm using C# here, but the same can be done easily in VB.NET, too.
// Define your database and table you want to script out
string dbName = "YourDatabase";
string tableName = "YourTable";
// set up the SMO server objects - I'm using "integrated security" here for simplicity
Server srv = new Server();
srv.ConnectionContext.LoginSecure = true;
srv.ConnectionContext.ServerInstance = "YourSQLServerInstance";
// get the database in question
Database db = new Database();
db = srv.Databases[dbName];
StringBuilder sb = new StringBuilder();
// define the scripting options - what options to include or not
ScriptingOptions options = new ScriptingOptions();
options.ClusteredIndexes = true;
options.Default = true;
options.DriAll = true;
options.Indexes = true;
options.IncludeHeaders = true;
// script out the table's creation
Table tbl = db.Tables[tableName];
StringCollection coll = tbl.Script(options);
foreach (string str in coll)
{
sb.Append(str);
sb.Append(Environment.NewLine);
}
// you can get the string that makes up the CREATE script here
// do with this CREATE script whatever you like!
string createScript = sb.ToString();
You need to reference several SMO assemblies.
Read more about SMO and how to use it here:
Getting Started with SQL Server Management Objects (SMO)
Generate Scripts for database objects with SMO for SQL Server

Related

Query across two SQLite databases in Delphi TFDQuery [duplicate]

I have an application that uses a SQLite database and everything works the way it should. I'm now in the process of adding new functionalities that require a second SQLite database, but I'm having a hard time figuring out how to join tables from the different databases.
If someone can help me out with this one, I'd really appreciate it!
Edit: See this question for an example case you can adapt to your language when you attach databases as mentioned in the accepted answer.
If ATTACH is activated in your build of Sqlite (it should be in most builds), you can attach another database file to the current connection using the ATTACH keyword. The limit on the number of db's that can be attached is a compile time setting(SQLITE_MAX_ATTACHED), currently defaults to 10, but this too may vary by the build you have. The global limit is 125.
attach 'database1.db' as db1;
attach 'database2.db' as db2;
You can see all connected databases with keyword
.databases
Then you should be able to do the following.
select
*
from
db1.SomeTable a
inner join
db2.SomeTable b on b.SomeColumn = a.SomeColumn;
Note that "[t]he database names main and temp are reserved for the primary database and database to hold temporary tables and other temporary data objects. Both of these database names exist for every database connection and should not be used for attachment".
Here is a C# example to complete this Question
/// <summary>
/// attachSQL = attach 'C:\\WOI\\Daily SQL\\Attak.sqlite' as db1 */
/// path = "Path of the sqlite database file
/// sqlQuery = #"Select A.SNo,A.MsgDate,A.ErrName,B.SNo as BSNo,B.Err as ErrAtB from Table1 as A
/// inner join db1.Labamba as B on
/// A.ErrName = B.Err";
/// </summary>
/// <param name="attachSQL"></param>
/// <param name="sqlQuery"></param>
public static DataTable GetDataTableFrom2DBFiles(string attachSQL, string sqlQuery)
{
try
{
string conArtistName = "data source=" + path + ";";
using (SQLiteConnection singleConnectionFor2DBFiles = new SQLiteConnection(conArtistName))
{
singleConnectionFor2DBFiles.Open();
using (SQLiteCommand AttachCommand = new SQLiteCommand(attachSQL, singleConnectionFor2DBFiles))
{
AttachCommand.ExecuteNonQuery();
using (SQLiteCommand SelectQueryCommand = new SQLiteCommand(sqlQuery, singleConnectionFor2DBFiles))
{
using (DataTable dt = new DataTable())
{
using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(SelectQueryCommand))
{
adapter.AcceptChangesDuringFill = true;
adapter.Fill(dt);
return dt;
}
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Use Process Exception method An error occurred");
return null;
}
}
Well, I don't have much experience with SQLite you have to access both databases in a single query.
You can have something like :
select name from DB1.table1 as a join DB2.table2 as b where a.age = b.age;
In databases like SQLServer you can access other databases in this hierarchical fashion, this should also work for SQLite.
I think you can initiate an instance of sqlite with more than 1 databases !

Create a Sql Azure Database with serverless tier using SDK

Currently, I create databases and attach them to an SQL elastic pool:
database = await sqlServer.Databases.Define(mainDb.DbName).WithExistingElasticPool(pool.Name).CreateAsync();
Instead, I want to create databases with tier "General Purpose: Serverless, Gen5, 1 vCore", but I couldn't find any method that offers that possibility.
This feature is still in preview, I can't find anything on the forums on this. How can I achieve this?
As an addendum to #Jim Xu accepted answer, the API has changed.
var database = sqlserver.Databases.Define("test").WithEdition("GeneralPurpose").WithServiceObjective("GP_S_Gen5_1").Create();
The WithEdition is now a DatabaseEdition edition type, and WithServiceObjective is now a ServiceObjectiveName. Both of these are muddled string enums with lists of version types. They do both also accept a .Parse() method. So the line should now be:
var database = sqlserver.Databases.Define("test")
.WithEdition(**Database.Edition.Parse("GeneralPurpose")**)
.WithServiceObjective(**ServiceObjectiveName.Parse("GP_S_Gen5_1")**)
.Create();
According to my test, we can use the following c# code to create "General Purpose: Serverless, Gen5, 1 vCore" database
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(client,key,tenant,AzureEnvironment.AzureGlobalCloud);
var azure = Azure.Configure().Authenticate(credentials).WithSubscription(SubscriptionId);
var sqlserver=azure.SqlServers.GetById("/subscriptions/<your subscrption id>/resourceGroups/<your resource group name>/providers/Microsoft.Sql/servers/<your server name>");
var database = sqlserver.Databases.Define("test").WithEdition("GeneralPurpose").WithServiceObjective("GP_S_Gen5_1").Create();
Console.WriteLine(database.ServiceLevelObjective);
Console.WriteLine(database.Edition);
Console.WriteLine(database.Name);
Console.ReadLine();
Please reference this tutorial: Create a new elastic database pool with C#.
It provides the code example about Create a new database in a pool:
Create a DataBaseCreateorUpdateProperties instance, and set the properties of the new database. Then call the CreateOrUpdate method with the resource group, server name, and new database name.
// Create a database: configure create or update parameters and properties explicitly
DatabaseCreateOrUpdateParameters newPooledDatabaseParameters = new DatabaseCreateOrUpdateParameters()
{
Location = currentServer.Location,
Properties = new DatabaseCreateOrUpdateProperties()
{
Edition = "Standard",
RequestedServiceObjectiveName = "ElasticPool",
ElasticPoolName = "ElasticPool1",
MaxSizeBytes = 268435456000, // 250 GB,
Collation = "SQL_Latin1_General_CP1_CI_AS"
}
};
var poolDbResponse = sqlClient.Databases.CreateOrUpdate("resourcegroup-name", "server-name", "Database2", newPooledDatabaseParameters);
Please try to replace "standard" with the price tier "General Purpose: Serverless, Gen5, 1 vCore".
Hope this helps.

How to show a table from a SQL Server database by using SqlKata?

I am trying to show a table from a database in my SQL Server 2017 by using SqlKata.
I have browsed for some researches. Based from one of the articles, I need to write this command var books = db.Query("Books").Get();
My question here is: Where do we put the command in a C# .NETCoreApp 1.1 target framework file? And how to run to display out the result?
If you have a cast class use
var books = db.Query("Books").Get<YouClass>();
But you dont have cast class -> use
var books = db.Query("Books").Get<dynamic>();
If you want logging execute query, write code startup.cs
var db = new QueryFactory(connection, new SqlServerCompiler());
// Log the compiled query to the console
db.Logger = compiled => {
Console.WriteLine(compiled.ToString()); //NLog - GrayLog - API - DB - TextFile - more..
};
etc. https://sqlkata.com/docs/execution/logging

Create Calculated tables in SSAS Tabular Model using Tabular Object Model Program Scripts

I am trying to create an SSAS Tabular database dynamically using the Tabular Object Model (TOM) C# scripts. I am able to create all the components of the tabular Model except for calculated tables and I am unable to find any solutions online.
Any insight on the same is highly appreciated.
Thanks
This can be done through executing a TMSL command that is the DDL for the calculated table using an OLE DB connection with the MSOLAP provider. First the command will need to be executed to create the calculated table. Next the table will need to be processed for it to be available for use, which is covered in the second part of the example below. The same connection string can be used for the both OLE DB and SSAS connection. Make sure properly escape any \ or " in the TMSL command, as well as set the Extended Properties and Provider properties accordingly in the connection string.
string connString = "Data Source=YourSSASInstance;Initial Catalog=YourTabularDatabase;Provider=MSOLAP.7;Integrated Security=SSPI;Extended Properties=Format=Tabular;";
using (OleDbConnection oleDBConn = new OleDbConnection(connString))
{
OleDbCommand oleDBCmd = new OleDbCommand(commandWithTMSL);
oleDBCmd.Connection = oleDBConn;
oleDBConn.Open();
oleDBCmd.ExecuteNonQuery();
}
using (Microsoft.AnalysisServices.Tabular.Server serv = new Microsoft.AnalysisServices.Tabular.Server())
{
serv.Connect(connString);
Microsoft.AnalysisServices.Tabular.Database db = serv.Databases["YourTabularDatabase"];
Model m = db.Model;
m.Tables["NewCalculatedTable"].RequestRefresh(RefreshType.Full);
m.SaveChanges();
}

Upload and Download error synchronizing Sql Server and Sql Azure - Sync Framework

I'm trying to synchronize an Sql Server database with SQL Azure Database (please be patient 'cause I don't fully understand Sync Framework). These are the requirements:
First: synchronize 1 table from Sql Azure to Sql Server
Second: synchronize 13 other tables (including the table I mentioned in the first step) from Sql Server to Azure.
I've created a console application, and this is the code:
1.I create one scope with the 13 tables:
DbSyncScopeDescription myScope = new DbSyncScopeDescription("alltablesyncgroup");
DbSyncTableDescription table = qlSyncDescriptionBuilder.GetDescriptionForTable("tablename", sqlServerConn);
myScope.Tables.Add(table); //repeated 13 times.
2.I Provision both data bases:
SqlSyncScopeProvisioning sqlAzureProv = new SqlSyncScopeProvisioning(sqlAzureConn,myScope);
if (!sqlAzureProv.ScopeExists("alltablesyncgroup"))
{
sqlAzureProv.Apply();
}
SqlSyncScopeProvisioning sqlServerProv = new SqlSyncScopeProvisioning(sqlServerConn, myScope);
if (!sqlServerProv.ScopeExists("alltablesyncgroup"))
{
sqlServerProv.Apply();
}
3.I create the SyncOrchestrator with the SyncDirectionOrder.Download to sync the firts table:
SqlConnection sqlServerConn = new SqlConnection(sqllocalConnectionString);
SqlConnection sqlAzureConn = new SqlConnection(sqlazureConnectionString);
SyncOrchestrator orch = new SyncOrchestrator
{
RemoteProvider = new SqlSyncProvider(scopeName, sqlAzureConn),
LocalProvider = new SqlSyncProvider(scopeName, sqlServerConn),
Direction = SyncDirectionOrder.Download
};
orch.Synchronize();
4.Later, I use the same function only changing the direction SyncDirectionOrder.Upload to sync the 13 remaining tables
SqlConnection sqlServerConn = new SqlConnection(sqllocalConnectionString);
SqlConnection sqlAzureConn = new SqlConnection(sqlazureConnectionString);
SyncOrchestrator orch = new SyncOrchestrator
{
RemoteProvider = new SqlSyncProvider(scopeName, sqlAzureConn),
LocalProvider = new SqlSyncProvider(scopeName, sqlServerConn),
Direction = SyncDirectionOrder.Upload
};
orch.Synchronize();
Now, here is the thing, obviously I'm doing it wrong 'cause when I download, the syncStats shows that a lot of change have been applied BUT I can't see it reflected on any data base and when I try to execute the Upload sync it seems to be going into a loop 'cause the Upload process doesn't stop.
Thanks!!!
first, you mentioned you only want to sync one table from Azure to your SQL Server but you're provisioning 13 tables in the scope. if you want one table, just provision a scope with one table. (e.g. one scope for the download with table, one scope for the upload with the rest of the tables)
to find out why rows are not synching, you can subscribe to the ApplyChangeFailed event for both sides, and check if there are conflicts or errors being encountered.
or you can enable Sync Framework tracing in verbose mode so you can see what's happening underneath.