European Windows 2012 Hosting BLOG

BLOG about Windows 2012 Hosting and SQL 2012 Hosting - Dedicated to European Windows Hosting Customer

SQL Server Hosting - HostForLIFE :: In SQL Server 2012, Copy a Table Containing Data from One Database to Another

clock May 27, 2025 08:35 by author Peter

In a SQL Server database, this article shows how to replicate a table containing data between databases. This article uses a source database that has a table with data in it and creates a new database that has a copy of the source database's table with data in it. This article outlines a few easy ways to accomplish this. Let's now examine a real-world example of how to transfer a table containing data between databases in SQL Server. The SQL Server Management Studio is used to create the example on SQL Server.Creating a table in SQL Server

Now we create a table named employee using.
CREATE TABLE [dbo].[Employee]
(
    [EmpID] [int] NULL,
    [EmpName] [varchar](30) NULL,
    [EmpSalary] [int] NULL
)


The following is the sample data for the employee table.

Method 1. Copy Table using SELECT INTO
This command only copies a table's schema and its data. The Select into is used to copy a table with data from one database to another database's table. The Select into is also used to create a new table in another database. The general syntax to do that is:

Syntax
SELECT * INTO DestinationDB.dbo.tableName FROM SourceDB.dbo.SourceTable

Example
The employee table is defined in the master database. It is also called the source database. Now you want to copy the table with data from the master database to the model database. The following query defines it:
SELECT * INTO Model.dbo.[Employee] FROM Master.dbo.[Employee]

Now hit F5 to execute it.

Now press F8 to open the Object Explorer and select the model database to see the employee table.

Method 2. Generating Script in SQL Server
If you want to copy all objects, indexes, triggers, constraints, etc., do it using "Generate Scripts...". Suppose we have a database named Test. Now right-click on the Test database and select the "Generate Scripts..." option.

database Name -> "Tasks" -> "Generate Scripts...."

Now click on "Generate Scripts...". The Generate Scripts wizard will be opened.

Now click the "Next" Button and select tables and Stored Procedures.

Now click on the "Next" Button and provide the proper name with the file's path.

Now click the "Next" Button and review your source and target location.

Now click on the "Next" Button.

Now finally, click on the "Finish" button. The script file has been generated for the Test database. To see the generated script file, select the file's location on your computer.

Creating a Database in SQL Server
These are the following steps to create a new database:

  • Press F8 to open the Object Browser in SQL Server Management Studio and expand it
  • Database -> right-click-> select New database
  • This would open the "New Database" window
  • Now enter a database name to create a database
  • Now click on the OK button to create the database. The new database will be shown in the Object Explorer

Currently, the database, named DatabaseTest, has been created.

Copy Database Schema and Data to Other Database
Now right-click on the script file, open it in Notepad, copy all the data, and paste it into the query window in SQL Server. It will look as in the following.

Now only change the database name test to DatabaseTest.

Now press F5 to execute the script and expand the databaseTest to see the schema and data.


Summary
This article taught us how to Copy Table With Data From One Database to Another in SQL Server.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server Hosting - HostForLIFE :: Using Dynamic SQL Script

clock May 22, 2025 09:58 by author Peter

A: Overview
SQL statements that are created and run at runtime in response to input parameters are known as dynamic SQL. Coding flexibility is increased by using dynamic SQL statements, however programming and maintenance will become more difficult. Additionally, a success concept like SQL Injection will be introduced (see What Is SQL Injection).

In general, we would say, dynamic SQL Script is no good, due to, at least, two reasons:

  1. Not readable, and not maintainable;
  2. Security, possible the target of SQL injection

Therefore, using dynamic SQL Script must be in the situation: 'have to'.

In our previous SDD database data input, Create a System Data Dictionary Database, we use dynamic SQL. Let us discuss the reasonabilities. The content of this article:

  • A - Introduction
  • B - Security is not a concern for using Dynamic SQL in a Stored Procedure
  • C - Requirement: Loop for Servers and Databases
    • C.1 - Get Servers (including linnked servers and remote servers) by SQL
    • C.2 - Get Databases by SQL
  • D - Looping Databases by Static SQL is not possible
    • D.1 - All system database, such as sys.object, are all within one database, except servers and databases,
    • D.2 - The USE key word cannot be used within a Stored Procedure
    • D.3 - The database Identifier cannot be parameterized.
  • E - Dynamic SQL Script is the only choice for Looping databases

B - Security is not a concern for using Dynamic SQL in a Stored Procedure
First, due to used in Stored Procedure, within firewall, and especially, there is no parameter input, so the security issue is almost zero. Let us see if this is a 'have to' situation.

C - Requirement: Loop for Servers and Databases

We need to create a database including all information about the whole databases in a Server, or at least one instance. We need to dynamically loop the databases existing in this server or instance.This is possible by

C.1 - Get Servers (including linnked servers and remote servers) by SQL

SELECT * FROM sys.servers

Contains a row per linked or remote server registered, and a row for the local server that has server_id = 0. Such as

C.2 - Get Databases by SQL
SELECT * FROM sys.databases

Contains one row per database in the instance of SQL Server.

D - Looping Databases by Static SQL is not possible
Due to the following reasons:

  • All system database, such as sys.object, are all within one database, except servers and databases,
  • The USE key word cannot be used within a Stored Procedure
  • The database Identifier cannot be parameterized.

We show these one by one.

D.1 - All system database, such as sys.object, are all within one database, except servers and databases,

In this page: sys.sysobjects , the definitiion says:

This ontains one row for each object that is created within a database

D.2 - The USE key word cannot be used within a Stored Procedure:
a USE database statement is not alloweed in a procedure, function or trigger:

if we try to use a USE statement in a stored procedure, we will see the error like above.

D.3 - we cannot use the dynamic database name in the schema identifier, such as

E - Dynamic SQL Script is the only choice for Looping databases
The following code sample is from the previous article: Create a System Data Dictionary Database

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server Hosting - HostForLIFE :: ObjectContext VS DBContext

clock May 15, 2025 10:09 by author Peter

Data can be queried and worked with as objects using ObjectContext and DbContext. Furthermore, the Unit of Work and Repository patterns can be combined to describe Dbcontext. DbContext and ObjectContext are conceptually equivalent.

ObjectContext
ObjectContext is a class that manages all the database operations, like database connection, and manages various entities of the Entity Model. We can say that ObjectContext is the primary class for accessing or working together with entities that are defined in the conceptual model.

ObjectContext is responsible for

  • Database connection
  • It provides built-in Add, Update and Delete functions
  • Object Set of every entity
  • Provide State of pending changes
  • It holds the changes done in entities

ObjectContext also encapsulates a few things

  • Connection to the Data Store or Database
  • Metadata in the Entity Data Model (EDM)
  • ObjectStateManager to track changes to the objects

DbContext
DbContext is conceptually similar to ObjectContext. DbContext is nothing but an ObjectContext wrapper, we can say it is a lightweight alternative to the ObjectContext. DbContext can be used for DataBase first, code first and model first development. DbContext mainly contains a set of APIs that are very easy to use. The API is exposed by ObjectContext. These APIs also allow us to use a Code First approach that ObjectContext does not allow.

ObjectContext VS DbContext

ObjectContext DbContext
ObjectContext class is part of the core Entity Framework API, which allows us to perform queries, change and track updates of the Database by using strongly typed entity classes. The DbContext class can be described as a wrapper of ObjectContext. It exposes the most commonly used features of ObjectContext.
ObjectContext supports Compiled Queries. DbContext does not support Compiled Queries.
ObjectContext supports the self-tracking of Entities DbContext does not support the self-tracking of Entities.
ObjectContext is only useful in Model First and Database First approaches DbContext is useful in the Model First, Database First approach as well as Code First approach.
ObjectContext can be used by Entity Framework 4.0 and below. DBContext can be used by Entity Framework 4.1 and above.
The ObjectContext class is not thread-safe. Any public static (C#) or Shared (Visual Basic) members of DbContext are thread-safe. Any instance members are not guaranteed to be thread-safe.

There are also many methods in common in both ObjectContext and DbContext. For example, ObjectContext has a direct method to execute a query against a database whereas the DbContext.Database class contains the SQLQuery method to obtain the same result.

Example
// using ObjectContext (EF4.0) using (
  Entities context = new Entities()
) {         IEnumerable < EmployeeDetails > empDetails   =  context.ExecuteStoreQuery < EmployeeDetails >     ("exec GetEmployeeData").ToList();
} // using DBContext (
  EF 4.1
  and above
) using (
  Entities context = new Entities()
) {         IEnumerable < EmployeeDetails > empDetails   =  context.Database.SqlQuery                                                                       < EmployeeDetails >("exec GetEmployeeData ", null).ToList();
}


DbContext also has some sets of methods that are not available with ObjectContext, like Dbset. Find, DbSet.Local etcetera.

Some of the ObjectContext methods are also renamed. For example, ObjectContext has methods like AddObject, DeleteObject, And Attach on ObjectSet<T>, in DbContext, they are named Add, Remove and Attach on DbSet<TEntity>.

Conclusion
Dbcontext can be defined as a lightweight version of the ObjectContext or we can say Dbcontext is a wrapper of ObjectContext and exposes only the common features that are really required in programming.

We can also get a reference to the ObjectContext from then DbContext to use those features that are only supported in ObjectContext.

The following code could help to get an ObjectContext Object from an existing DbContext Object.
public class EntityDBContext: DbContext,
IObjectContextAdapter {
ObjectContext IObjectContextAdapter.ObjectContext
{         get         {               var objectContext = (this as IObjectContextAdapter)               if(objectContext != null)
return (this as IObjectContextAdapter).ObjectContext;
              else                 return null;
        }    } }
Finally, DbContext is not a replacement for ObjectContext, but it is a simple alternative that builds on ObjectContext. Hope this will help to understand the differences between ObjectContext and DbContext.



SQL Server Hosting - HostForLIFE :: NoSQL vs. SQL: Which One to Use

clock May 5, 2025 09:51 by author Peter

"What are the differences between NoSQL and SQL databases?" is a question you've undoubtedly heard if you've taken part in a lot of interviews. You will gain a thorough understanding of these distinctions and when to pick one over the other from this essay.

As a software developer, you may have already worked with various SQL databases such as T-SQL, PostgreSQL, MySQL, and others. What's the first thing you've likely noticed? The "rules" or the "schema," of course. SQL databases have highly structured data models. You create tables with defined columns and rows, strictly following a predetermined schema. Breaking this structure means violating the fundamental principles of SQL. Tables, columns, rows, and data types form the essential building blocks for organizing your data.

On the other hand, when you work with NoSQL databases (non-relational databases) like Azure Cosmos DB, Aurora, or MongoDB, you have the flexibility to frequently modify your data model. NoSQL databases don't enforce a rigid structure. They provide an "elastic" schema, allowing you to store data in various formats. Instead of sticking to the traditional table representation, you can use document-based, key-value-based, graph-based, or column-based models, among others.

For relational databases, developers usually apply normalization (such as first normal form, second normal form, etc.) to ensure a clear and balanced data structure. As a result, relational databases often rely heavily on multi-table JOINs, aggregations, and complex relationships to retrieve data. However, when datasets become large, it can be challenging and inefficient to manage and retrieve data quickly from relational databases.

Unfortunately, relational databases aren't inherently designed to handle massive volumes of data. They follow a "scale-up" approach, meaning they require more resources such as RAM, CPU, and GPU to handle increased data.

NoSQL databases, however, are designed for "scaling out." This means you can distribute and handle data across multiple servers without negatively impacting performance. Many people associate "NoSQL" with "Big Data," often using these terms interchangeably. Indeed, you can consider the term "NoSQL" a buzzword frequently associated with solving big data challenges.

Behind NoSQL Lies the 3V Principle

  • Volume
  • Velocity
  • Variety


Let's examine each of these elements individually to understand their importance.

Volume refers to handling massive datasets, reaching terabytes, petabytes, and beyond. Thanks to the "scale-out" design, NoSQL databases comfortably manage vast amounts of data without issues. SQL databases, by comparison, often struggle with such extensive data sets due to limitations in hardware scaling and structured data constraints, making them less efficient for extremely large data scenarios.

Velocity is about throughput—handling massive amounts of simultaneous requests quickly and efficiently. NoSQL databases excel at processing high-velocity data streams, which is crucial for applications like social media feeds, real-time analytics, IoT applications, and more. SQL databases may experience bottlenecks due to their rigid schemas and transaction overhead, slowing down performance in high-throughput situations.

Variety emphasizes schema flexibility. You can utilize any of the schema forms mentioned previously or even choose a schema-less approach entirely. This schema flexibility means NoSQL databases can easily accommodate rapidly evolving data requirements, different data formats, and unstructured or semi-structured data like images, videos, and sensor data. Conversely, SQL databases are best suited for structured and consistent data that doesn't frequently change.

Let's explore more internal details between them.

  • Transactions and ACID Compliance: SQL databases generally offer strong consistency and ACID (Atomicity, Consistency, Isolation, Durability) compliance. NoSQL databases often sacrifice strict ACID compliance for scalability and flexibility, adopting eventual consistency models.
  • Complex Queries and Reporting: SQL databases excel in executing complex queries, and multi-table joins, and providing extensive reporting capabilities. NoSQL databases might require additional processing layers or specialized query mechanisms for complex analytical queries.
  • Scaling Approaches: SQL databases typically scale vertically (adding more resources to a single server), while NoSQL databases scale horizontally (adding more servers), providing more flexibility and efficiency for handling large datasets.

Understanding these differences and key characteristics will help you choose the right database solution based on your specific requirements. The best measure for your application is your context. The application context defines which one is perfect for you.

HostForLIFE.eu SQL Server 2022 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in