Pages

Search This Blog

Monday, March 25, 2013

Temporary Tables in SQL Server


Introduction

SQL Server provides the concept of temporary table which helps the developer in a great way. These tables can be created at runtime and can do the all kinds of operations that one normal table can do. But, based on the table types, the scope is limited. These tables are created inside tempdb database.
In this article, I am just going to give a quick overview for beginners on those temporary tables. Please give your valuable suggestions and feedback to improve this article.  

Different Types of Temporary Tables

SQL Server provides two types of temp tables based on the behavior and scope of the table. These are:
  • Local Temp Table
  • Global Temp Table

Local Temp Table

Local temp tables are only available to the current connection for the user; and they are automatically deleted when the user disconnects from instances. Local temporary table name is stared with hash ("#") sign.

Global Temp Table

Global Temporary tables name starts with a double hash ("##"). Once this table has been created by a connection, like a permanent table it is then available to any user by any connection. It can only be deleted once all connections have been closed.

Creating Temporary Table in SQL Server 2005

As I have already discussed, there are two types of temporary tables available. Here I am going to describe each of them.

Local Temporary Table

The syntax given below is used to create a local Temp table in SQL Server 2005:
CREATE TABLE #LocalTempTable(
UserID int,
UserName varchar(50), 
UserAddress varchar(150))
The above script will create a temporary table in tempdb database. We can insert or delete records in the temporary table similar to a general table like:
insert into #LocalTempTable values ( 1, 'Abhijit','India');
Now select records from that table:
select * from #LocalTempTable
After execution of all these statements, if you close the query window and again execute "Insert" or "Select"Command, it will throw the following error:
Msg 208, Level 16, State 0, Line 1
Invalid object name '#LocalTempTable'.
This is because the scope of Local Temporary table is only bounded with the current connection of current user.

Global Temporary Table

The scope of Global temporary table is the same for the entire user for a particular connection. We need to put "##"with the name of Global temporary tables. Below is the syntax for creating a Global Temporary Table:  
CREATE TABLE ##NewGlobalTempTable(
UserID int,
UserName varchar(50), 
UserAddress varchar(150))
The above script will create a temporary table in tempdb database. We can insert or delete records in the temporary table similar to a general table like:
insert into ##NewGlobalTempTable values ( 1, 'Abhijit','India');
Now select records from that table:
select * from ##NewGlobalTempTable
Global temporary tables are visible to all SQL Server connections. When you create one of these, all the users can see it.

Storage Location of Temporary Table

Temporary tables are stored inside the Temporary Folder of tempdb. Whenever we create a temporary table, it goes to Temporary folder of tempdb database.
TempTableLocation.JPG
Now, if we deeply look into the name of Local Temporary table names, a 'dash' is associated with each and every table name along with an ID. Have a look at the image below:
LocalTable.JPG - Click to enlarge image
SQL server does all this automatically, we do not need to worry about this; we need to only use the table name.  

When to Use Temporary Tables?

Below are the scenarios where we can use temporary tables:
  • When we are doing large number of row manipulation in stored procedures.
  • This is useful to replace the cursor. We can store the result set data into a temp table, then we can manipulate the data from there.
  • When we are having a complex join operation.

Points to Remember Before Using Temporary Tables

  • Temporary table created on tempdb of SQL Server. This is a separate database. So, this is an additional overhead and can causes performance issues.
  • Number of rows and columns need to be as minimum as needed.
  • Tables need to be deleted when they are done with their work.

Alternative Approach: Table Variable

Alternative of Temporary table is the Table variable which can do all kinds of operations that we can perform inTemp table. Below is the syntax for using Table variable.
Declare @TempTableVariable TABLE(
UserID int,
UserName varchar(50), 
UserAddress varchar(150))
The below scripts are used to insert and read the records for Tablevariables:
insert into @TempTableVariable values ( 1, 'Abhijit','India');
Now select records from that tablevariable:
select * from @TempTableVariable

When to Use Table Variable Over Temp Table

Tablevariable is always useful for less data. If the result set returns a large number of records, we need to go for temp table.

SQL Server - Server Roles


When creating a new user login in SQL Server, you get the option of assigning the login one or more server roles.
Server roles (not to be confused with database roles) are available for various database administration tasks. Not everyone should be assigned to a server role. In fact, only advanced users such as database administrators should be assigned a server role.

Accessing the Server Roles

To access the server roles in SQL Server Management Studio, expand the Security folder:
Screenshot of accessing server roles
You view the properties of a server role by right clicking on it. You can then add users to the server role by clicking Add. In the screenshot below, Homer has been added to the securityadmin role.
Adding a user to a server role

Explanation of Server Roles

Here's an explanation of the server roles defined in SQL Server 2008 during setup:
Server RoleDescription
sysadminCan perform any task in SQL Server.
serveradminCan set server-wide configuration options, can shut down the server.
setupadminCan manage linked servers and startup procedures.
securityadminCan manage logins and database permissions, read logs, change passwords.
processadminCan manage processes running in SQL Server.
dbcreatorCan create, alter, and drop databases.
diskadminCan manage disk files.
bulkadminCan execute BULK INSERT statements.
publicEvery SQL Server user account belongs to this server role. When a server principal has not been granted or denied specific permissions on a securable object, the user inherits the permissions granted to public on that object. Only assign public permissions on an object when you want the object to be available to all users.
As you can see, some of these roles allow very specific tasks to be performed. If you don't have many technical users, it's likely that you'll only use one or two of these roles (including sysadmin).

SQL Server - User Logins


SQL Server allows for the creation of user logins. Each individual who needs access to SQL Server can be given their own user account.
When the administrator configures these user logins, he/she can assign them to any number of roles and schemas, depending on the access that the individual is entitled to.
In this lesson, we will walk through the steps in creating a user login.

To Create a New User Login

  1. Using SQL Server Management Studio, expand the "Security" option and right click on "Logins"
  2. Click on "New Login"
    Creating a new login in SQL Server
  3. Complete the login properties in the "General" tab by providing a name for the login, choosing the Authentication method (providing a password if you choose "SQL Server authentication"), and selecting the database to use as a default. If you don't choose a language, it will use the default for the current installation of SQL Server.
    If you get an error that reads "The MUST_CHANGE option is not supported by this version of Microsoft Windows", simply uncheck the "User must change password at next login" option. The error occurs because your operating system doesn't support this option.

    Creating a new login in SQL Server - General tab
  4. Click the "Server Roles" tab if you need to apply any server-wide security privileges.
    Creating a new login in SQL Server - Server Roles tab
  5. Click the "User Mapping" tab to specify which databases this user account is allowed to access. By default, the login will be assigned to the "Public" role, which provides the login with basic access. If the login needs more access in one or more databases, it can be assigned to another role with greater privileges.Note that these roles are "Database Roles" and are different to the server roles in the previous tab. Server roles are for administering the SQL Server. Database roles are created within each database and specify what the login can do within that database.
    Creating a new login in SQL Server - User Mapping tab

SQL Server - Database Schemas


Ever since SQL Server 2005 was released, each object in a database has belonged to a database schema. SQL Server 2008 has continued with database schemas, and an explanation follows.

What is a Database Schema?

A database schema is a way to logically group objects such as tables, views, stored procedures etc. Think of a schema as a container of objects.
You can assign a user login permissions to a single schema so that the user can only access the objects they are authorized to access.
Schemas can be created and altered in a database, and users can be granted access to a schema. A schema can be owned by any user, and schema ownership is transferable.

Creating a Database Schema

To create a database schema in SQL Server 2008:
  1. Navigate to Security > Schemas
  2. Right click on Schemas and select New Schema.... Like this:
    Creating a database schema in SQL Server Management Studio
  3. Complete the details in the General tab for the new schema. In this example, the schema name is "person" and the schema owner is "Homer".
    Creating a database schema in SQL Server Management Studio
  4. Add users to the schema as required and set their permissions:
    Creating a database schema in SQL Server Management Studio
  5. Add any extended properties (via the Extended Properties tab)
  6. Click OK.

Add a Table to the New Schema

Now that we have a new schema, we can add objects such as tables, views, and stored procedures to it. For example, we could transfer the table that we created in the earlier lesson to the new schema.
When we created that table (called "Individual"), it was created in the default database schema ("dbo"). We know this because it appears in our object browser as "dbo.Individual".
To transfer the "Individual" table to the person "schema":
  1. In Object Explorer, right click on the table name and select "Design":
    Changing database schema for a table in SQL Server Management Studio
  2. From Design view, press F4 to display the Properties window.
  3. From the Properties window, change the schema to the desired schema:
    Changing database schema for a table in SQL Server Management Studio
  4. Close Design View by right clicking the tab and selecting "Close":
    Closing Design View
  5. Click "OK" when prompted to save
Your table has now been transferred to the "person" schema.

Confirm your Change

To confirm the change:
  1. Refresh the Object Browser view:
    Refreshing the view in Object Browser
  2. You will now see that Object Browser displays the new schema for the table (person.Individual):
    Screenshot of the table in Object Browser

Monday, March 11, 2013

New Features in SQL SERVER 2008


  • Transparent Data Encryption
    Enable encryption of an entire database, data files, or log files, without the need for application changes. Benefits of this include: Search encrypted data using both range and fuzzy searches, search secure data from unauthorized users, and data encryption without any required changes in existing applications.
  • Extensible Key Management
    SQL Server 2005 provides a comprehensive solution for encryption and key management. SQL Server 2008 delivers an excellent solution to this growing need by supporting third-party key management and HSM products.
  • Auditing
    Create and manage auditing via DDL, while simplifying compliance by providing more comprehensive data auditing. This enables organizations to answer common questions, such as, "What data was retrieved?"

  • Enhanced Database Mirroring
    SQL Server 2008 builds on SQL Server 2005 by providing a more reliable platform that has enhanced database mirroring, including automatic page repair, improved performance, and enhanced supportability.
  • Automatic Recovery of Data Pages
    SQL Server 2008 enables the principal and mirror machines to transparently recover from 823/824 types of data page errors by requesting a fresh copy of the suspect page from the mirroring partner transparently to end users and applications.
  • Log Stream Compression
    Database mirroring requires data transmissions between the participants of the mirroring implementations. With SQL Server 2008, compression of the outgoing log stream between the participants delivers optimal performance and minimizes the network bandwidth used by database mirroring.

  • Resource Governor
    Provide a consistent and predictable response to end users with the introduction of Resource Governor, allowing organizations to define resource limits and priorities for different workloads, which enable concurrent workloads to provide consistent performance to their end users.
  • Predictable Query Performance
    Enable greater query performance stability and predictability by providing functionality to lock down query plans, enabling organizations to promote stable query plans across hardware server replacements, server upgrades, and production deployments.
  • Data Compression
    Enable data to be stored more effectively, and reduce the storage requirements for your data. Data compression also provides significant performance improvements for large I/O bound workloads, like data warehousing.
  • Hot Add CPU
    Dynamically scale a database on demand by allowing CPU resources to be added to SQL Server 2008 on supported hardware platforms without forcing any downtime on applications. Note that SQL Server already supports the ability to add memory resources online.
  • Policy-Based ManagementPolicy-Based Management is a policy-based system for managing one or more instances of SQL Server 2008. Use this with SQL Server Management Studio to create policies that manage entities on the server, such as the instance of SQL Server, databases, and other SQL Server objects.
  • Streamlined Installation
    SQL Server 2008 introduces significant improvements to the service life cycle for SQL Server through the re-engineering of the installation, setup, and configuration architecture. These improvements separate the installation of the physical bits on the hardware from the configuration of the SQL Server software, enabling organizations and software partners to provide recommended installation configurations.
  • Performance Data Collection
    Performance tuning and troubleshooting are time-consuming tasks for the administrator. To provide actionable performance insights to administrators, SQL Server 2008 includes more extensive performance data collection, a new centralized data repository for storing performance data, and new tools for reporting and monitoring.
  • Language Integrated Query (LINQ)
    Enable developers to issue queries against data, using a managed programming language, such as C# or VB.NET, instead of SQL statements. Enable seamless, strongly typed, set-oriented queries written in .NET languages to run against ADO.NET (LINQ to SQL), ADO.NET DataSets (LINQ to DataSets), the ADO.NET Entity Framework (LINQ to Entities), and to the Entity Data Service Mapping provider. Use the new LINQ to SQL provider that enables developers to use LINQ directly on SQL Server 2008 tables and columns.
  • ADO.NET Data Services
    The Object Services layer of ADO.NET enables the materialization, change tracking, and persistence of data as CLR objects. Developers using the ADO.NET framework can program against a database, using CLR objects that are managed by ADO.NET. SQL Server 2008 introduces more efficient, optimized support that improves performance and simplifies development.
  • DATE/TIME
    SQL Server 2008 introduces new date and time data types:
    • DATE—A date-only type
    • TIME—A time-only type
    • DATETIMEOFFSET—A time-zone-aware datetime type
    • DATETIME2—A datetime type with larger fractional seconds and year range than the existing DATETIME type
    The new data types enable applications to have separate data and time types while providing large data ranges or user defined precision for time values.
  • HIERARCHY ID
    Enable database applications to model tree structures in a more efficient way than currently possible. New system type HierarchyId can store values that represent nodes in a hierarchy tree. This new type will be implemented as a CLR UDT, and will expose several efficient and useful built-in methods for creating and operating on hierarchy nodes with a flexible programming model.
  • FILESTREAM Data
    Allow large binary data to be stored directly in an NTFS file system, while preserving an integral part of the database and maintaining transactional consistency. Enable the scale-out of large binary data traditionally managed by the database to be stored outside the database on more cost-effective storage without compromise.
  • Integrated Full Text Search
    Integrated Full Text Search makes the transition between Text Search and relational data seamless, while enabling users to use the Text Indexes to perform high-speed text searches on large text columns.
  • Sparse Columns
    NULL data consumes no physical space, providing a highly efficient way of managing empty data in a database. For example, Sparse Columns allows object models that typically have numerous null values to be stored in a SQL Server 2005 database without experiencing large space costs.
  • Large User-Defined Types
    SQL Server 2008 eliminates the 8-KB limit for User-Defined Types (UDTs), allowing users to dramatically expand the size of their UDTs.
  • Spatial Data Types
    Build spatial capabilities into your applications by using the support for spatial data.
    • Implement Round Earth solutions with the geography data type. Use latitude and longitude coordinates to define areas on the Earth's surface.
    • Implement Flat Earth solutions with the geometry data type. Store polygons, points, and lines that are associated with projected planar surfaces and naturally planar data, such as interior spaces.
  • Backup Compression
    Keeping disk-based backups online is expensive and time-consuming. With SQL Server 2008 backup compression, less storage is required to keep backups online, and backups run significantly faster since less disk I/O is required.
  • Partitioned Table Parallelism
    Partitions enable organizations to manage large growing tables more effectively by transparently breaking them into manageable blocks of data. SQL Server 2008 builds on the advances of partitioning in SQL Server 2005 by improving the performance on large partitioned tables.
  • Star Join Query Optimizations
    SQL Server 2008 provides improved query performance for common data warehouse scenarios. Star Join Query optimizations reduce query response time by recognizing data warehouse join patterns.
  • Grouping Sets
    Grouping Sets is an extension to the GROUP BY clause that lets users define multiple groupings in the same query. Grouping Sets produces a single result set that is equivalent to a UNION ALL of differently grouped rows, making aggregation querying and reporting easier and faster.
  • Change Data Capture
    With Change Data Capture, changes are captured and placed in change tables. It captures complete content of changes, maintains cross-table consistency, and even works across schema changes. This enables organizations to integrate the latest information into the data warehouse.
  • MERGE SQL Statement
    With the introduction of the MERGE SQL Statement, developers can more effectively handle common data warehousing scenarios, like checking whether a row exists, and then executing an insert or update.
  • SQL Server Integration Services (SSIS) Pipeline Improvements
    Data Integration packages can now scale more effectively, making use of available resources and managing the largest enterprise-scale workloads. The new design improves the scalability of runtime into multiple processors.
  • SQL Server Integration Services (SSIS) Persistent Lookups
    The need to perform lookups is one of the most common ETL operations. This is especially prevalent in data warehousing, where fact records need to use lookups to transform business keys to their corresponding surrogates. SSIS increases the performance of lookups to support the largest tables.
  • Analysis Scale and Performance
    SQL Server 2008 drives broader analysis with enhanced analytical capabilities and with more complex computations and aggregations. New cube design tools help users streamline the development of the analysis infrastructure enabling them to build solutions for optimized performance.
  • Block Computations
    Block Computations provides a significant improvement in processing performance enabling users to increase the depth of their hierarchies and complexity of the computations.
  • Writeback
    New MOLAP enabled writeback capabilities in SQL Server 2008 Analysis Services removes the need to query ROLAP partitions. This provides users with enhanced writeback scenarios from within analytical applications without sacrificing the traditional OLAP performance.
  • Enterprise Reporting Engine
    Reports can easily be delivered throughout the organization, both internally and externally, with simplified deployment and configuration. This enables users to easily create and share reports of any size and complexity.
  • Internet Report Deployment
    Customers and suppliers can effortlessly be reached by deploying reports over the Internet.
  • Manage Reporting Infrastructure
    Increase supportability and the ability to control server behaviour with memory management, infrastructure consolidation, and easier configuration through a centralized store and API for all configuration settings.
  • Report Builder Enhancements
    Easily build ad-hoc and author reports with any structure through Report Designer.
  • Forms Authentication Support
    Support for Forms authentication enables users to choose between Windows and Forms authentication.
  • Report Server Application Embedding
    Report Server application embedding enables the URLs in reports and subscriptions to point back to front-end applications.
  • Microsoft Office Integration
    SQL Server 2008 provides new Word rendering that enables users to consume reports directly from within Microsoft Office Word. In addition, the existing Excel renderer has been greatly enhanced to accommodate the support of features, like nested data regions, sub-reports, as well as merged cell improvements. This lets users maintain layout fidelity and improves the overall consumption of reports from Microsoft Office applications.
  • Predictive Analysis
    SQL Server Analysis Services continues to deliver advanced data mining technologies. Better Time Series support extends forecasting capabilities. Enhanced Mining Structures deliver more flexibility to perform focused analysis through filtering as well as to deliver complete information in reports beyond the scope of the mining model. New cross-validation enables confirmation of both accuracy and stability for results that you can trust. Furthermore, the new features delivered with SQL Server 2008 Data Mining Add-ins for Office 2007 empower every user in the organization with even more actionable insight at the desktop

Constraints in SQL SERVER

A constraint is a restriction. Placed at either column or Table level, a constraint ensures that your data meets certain data integrity rules.
At a high level, there are 3 different types of constraints:
  • Entity Constraint
  • Domain Constraint.
  • Referential Integrity Constraints.