Sei sulla pagina 1di 73

SQL Server 2012 Tutorial

Below you will find article and How to on various SQL Server 2012 topics. This includes but not limited to different versions of SQL Server 2012, AlwaysOn Availability Groups, Transact SQL, different types of backups, installation guide, failover cluster installation guide, collation types and database server configuration. Version Datacenter Edition Summary Built on SQL Server 2012 Enterprise Edition, This version delivers a very highperforming data system that offers the highest levels of scalability for large deployments, virtualization and consolidation, and managing an Enterprises database infrastructure, helping companies to scale their mission-critical environment without too much cost. Enterprise Edition SQL Server 2012 Enterprise offers a all-inclusive data platform that delivers builtin security, high availability via AlwaysOn availability groups, and scalability, united with robust business intelligence contributions, allowing to enable the highest SLA for mission-critical Apps. Standard Edition
SQL Server 2012 Standard provides a complete data-management and BI platform for SMB small businesses to run their apps while requiring minimal IT aassistance.

SQL Server Standard for SMB small business edition includes all of the official components and features of SQL Server Standard but onlyallowed in a SMB small business environment of 75 or less systems.

SQL Server 2012 Basics: The Tools


The SQL Server DB Engine The DB Engine is the core app service in the SQL Server package for storing, processing, and securing data with SQL Server 2012. The SQL Server 2012 DB Engine is a Windows service that can be used to store and process data in a relational format, as XML documents, and new for 2012, as spatial data. The subsequent are the main responsibilities of the DB Engine:

Provide reliable storage for data Provide a means to rapidly retrieve this data Provide consistent access to the data Control access to the data throughout security Enforce data integrity rules to confirm that the data is reliable and consistent.

Each of these responsibilities is examined in greater detail in later chapters in this book.

Another key feature the DB Engine offers to confirm reliable storage is the transaction log. The transaction log makes a record of every change that is made to the DB. Another key feature the DB Engine offers to confirm reliable storage is the transaction log. The transaction log makes a record of every change that is made to the DB. SQL Server Management Studio SSMS is the central console from which most DB management tasks can be coordinated. SSMS offers a single interface from which all servers in a company can be managed. Subsequent are some of the tasks you can execute with SSMS. Most of these tasks are discussed in detail later in the book:

Completely manage many servers in a convenient interface Set server options and config values, such as the amount of memory and number of processors to use, default language, and default location of the data and log files Manage logins, DB users, and DB roles Create, edit, and schedule automated jobs throughout the SQL Server Agent Back up and restore DBs and define maintenance plans Create new DBs Browse table contents Create and manage DB objects, such as tables, indexes, and stored procedures Generate DDL scripts for DBs and DB objects Configure and manage replication Create, edit, execute, and debug Transact-SQL (T-SQL) scripts Define, implement, manage, and invoke SQL Server Policies Enable and disable features of SQL Server Manage and organize scripts into projects and save versions in source control systems such as Visual SourceSafe

SQL Server Config Manager SQL Server Config Manager is a tool provided with SQL Server 2012 for managing the services associated with SQL Server and for configuring the network protocols used by SQL Server. Primarily SQL Server Config Manager is used to start, pause, resume, and stop SQL Server services and to view or change service properties. SQL Server Agent SQL Server Agent is a scheduling tool integrated into SSMS that allows convenient definition and execution of scheduled scripts and maintenance jobs. SQL Server Agent also handles automated alertsas an example, if the DB runs out of space. SQL Server Agent is a Windows service that runs on the same machine as the SQL Server DB Engine. The SQL Server Agent service can be started and stopped throughout either SSMS, the SQL Server Config Manager, or

the ordinary Windows Services Manager. In enterprise situations in which many SQL Server machines need to be managed together, the SQL Server Agent can be configured to distribute common jobs to multiple servers throughout the use of Multiserver Administration. This ability is most helpful in a wide architecture scenario, in which many SQL Servers are performing the same tasks with the DBs. Jobs are managed from a single SQL Server machine, which is responsible for maintaining the jobs and distributing the job scripts to each target server. The results of each job are maintained on the target servers but can be observed throughout a single interface. If you had 20 servers that all needed to run the same job, you could check the completion status of that job in moments instead of logging in to each machine and checking the status 20 times.The SQL Server Agent also handles event forwarding. Any system events recorded in the Windows system event log can be forwarded to a single machine. This gives a busy admin a single place to look for errors. SQL Server Profiler The SQL Server Profiler is a GUI interface to the SQL Trace feature of SQL Server that captures the queries and results flowing to and from the DB engine. It is analogous to a network sniffer, although it does not operate on quite that low a level. The Profiler can capture and save a complete record of all the T-SQL commandss passed to the server and the occurrence of SQL Server events such as deadlocks, logins, and errors. You can use a series of filters to pare down the results when you can want to drill down to a single connection or even a single query. You can use the SQL Profiler to execute these helpful tasks:

You can capture the exact SQL statements sent to the server from an app for which source code is not available (as an example, third-party apps). You can capture all the queries sent to SQL Server for later playback on a test server. This ability is extremely useful for performance testing with live query traffic. If your server is encountering recurring access violations (AVs), you can use the Profiler to reconstruct what happened leading up to an AV. The Profiler displays basic performance data about each query. When your users start hammering your server with queries that cause hundreds of table scans, the Profiler can simply identify the culprits. For complex stored procedures, the Profiler can identify which portion of the procedure is causing the performance problem. You can audit server activity in real-time.

SQL Server 2012 Licensing Explained


In addition to feature sets, one of the decisive factors in choosing a SQL Server edition is cost. With SQL Server 2012, MS offers two types of licensing models: processor-based licensing and server-based licensing. Processor-based licensing involves a single license for each physical CPU in the machine that is running a MS Server product. This type of license includes unlimited client device access. Additional server licenses, seat licenses, and Internet connector licenses are not necessary. You need to purchase a processor license for each installed processor on the server on which SQL Server 2012 will be installed, even if some processors will not be used for

running SQL Server. The only exception is for systems with 16 or more processors that allow partitioning of the processors into groups so the SQL Server software can be delegated to a subset of the processors. For those who prefer the more familiar server/client access license (CAL), or for environments in which the number of client devices connecting to SQL Server is small and known, two server/CAL-based licensing models are also available:

Device CALsA device CAL is necessary for a device (as an example, PC, workstation, terminal, PDA, mobile phone) to access or use the services or functionality of MS SQL Server. The server plus device CAL model is likely to be the more cost operative choice if there are multiple users per device (as an example, in a call center). User CALsA SQL server user CAL is necessary for a user (as an example, an employee, a customer, a partner) to access or use the services or functionality of MS SQL Server. The server plus user CAL model is likely to be more cost effective if there are multiple devices per user (as an example, a user who has a desktop PC, laptop, PDA, and so forth).

The server/CAL licensing model involves purchasing a license for the computer running SQL Server 2012 as well as a license for each client device or user that accesses any SQL Server 2012 installation. A fixed number of CALs are included with a server license and the server software. Additional CALs can be purchased as needed. Server/per-seat CAL licensing is intended for environments in which the number of clients per server is relatively low, and admission from outside the company firewall is not necessary. Be aware that using a middle-tier or transaction server that pools or multiplexes DB connections does not reduce the number of CALs necessary. A CAL is still necessary for each distinct client workstation that connects throughout the middle tier. (Processor licensing might be preferable in these environments due to its simplicity and affordability when the number of clients is unknown and potentially large.)

SQL Server 2012 AlwaysOn Availability Groups


The AlwaysOn Availability Groups (AAG) feature is an HA and DR solution that provides an enterprises a substitute to DB mirror. New in MS SQL Server 2012, AlwaysOn Availability Groups make the best use of the availability of a set of user databases for an enterprise. Installing AlwaysOn Availability Groups involves creating and configuring one or more availability groups. Each availability group is a place holder for a distinct set of user databases, known as AlwaysOn availability databases, that allows failover. An AlwaysOn availability group can require multiple possible failover targets (secondary DB copy replicas). Furthermore, you may configure secondary DB replicas to support read-only access to secondary databases and for running backup against the secondary DB. AlwaysOn Availability Groups offers a rich set of choices that increase database availability and that allow improved resource use. The main mechanisms are as follows:

Supports one primary database replica and allows up to 4 secondary database replicas targets. Asynchronous-commit mode. This availability mode is a DR solution that works great when the availability replica copies are distributed with not so stable connection. Synchronous-commit mode. This availability mode put emphasis on high availability and allows data protection over performance, con is transaction latency. Allows automatic page restoration against page corruption. Backupable and Read-only access to the secondary databases Fast application failover is provided by availability group listeners. The greater failover control is achieved by Flexible failover policy.

Database Replicas Basics

Each AlwaysOn availability group designates two or more failover associates known as availability replicas (db copies). Database Availability replicas are components of the availability group that are held by separate instances of SQL Server be present in on different nodes of a WSFC failover cluster. Each server instances is either one a failover cluster instance (FCI) or standalone instance on which you require enabled AlwaysOn Availability Groups. Each availability replica hosts a copy of the AlwaysOn availability databases in the availability group. Every availability replica copy is assigned apreliminary role which designatesprimary role or the secondary role, which is congenital by the availability databases of that replica. The role of a given replica controls whether it hosts readwrite databases or readonly databases. primary replica, is assigned the primary role and hosts readwrite databases, which is a primary databases. At minimum one extra replica, known as a secondary replica, is assigned the secondary role. A secondary replica hosts read-only databases, known as secondary databases. To add a database copy to an AlwaysOn availability group, the database must be an online database and read-write database that exists on the server-instance that clouds the primary replica. When you add a database, it joins the AlwaysOn availability group as a primary database, while remaining available to clients. No conforming secondary database exists until backups of the new primary database are repaired to the server instance that hosts the secondary replica (using RESTORE WITH NORECOVERY). The new secondary db is in the RESTORING state until it is linked to AlwaysOn availability group. By joining, this places the secondary database into an ONLINE state and starts data syncwith the conforming primary database. Data synchronization is the procedure by which makes alterations to a primary database are copied on a secondary database. Data synchronization contains the primary replica sending transaction log records for the primary database to the secondary replica, this writes the transaction log archives to disk (hardens the log) and spread on the log records to the secondary database.

AlwaysOn Availability Modes The availability mode is a property of each of the availability replica. This regulates whether the

primary replica waits to commit transactions on a database until secondary copy write the transaction log records to disk . AlwaysOn Availability Groups allows two modes asynchronous-commit mode and synchronous-commit mode.

Asynchronous-commit mode asynchronous-commit mode allows the primary replica commits transactions without waiting for acknowledgement that an asynchronous-commit secondary replica has hardened the log. Asynchronous-commit mode minimizes transaction latency on the secondary databases but allows them to lag behind the primary databases, making some data loss possible. Synchronous-commit mode How synchronous-commit mode works is, before committing transactions, a synchronous-commit primary replica delays for a synchronous-commit secondary replica to grant that it has finished hardening the log. Synchronous-commit mode guarantees that once a given secondary database is synchronized with the primary database, committed transactions are fully safe. This safetyfeature down side is that it increases transaction latency.

Various Type of Failovers Within the environment of a session between the primaryreplica and a secondaryreplica, the primary and secondaryroles are possiblyexchangeable in a process known as failover. Secondary replica transitions to the primary role during this process, and it becomes the new primary replica. The new primaryreplica brings its databases online as the primary databases, and server apps can connect to it. When the previous primary replica is available, it transitions to the secondary role. The earlier primary databases become secondary databases and data synchronization continues. These are different type of failovers, automatic, manual, and forced. The method of failover supported by a arranged secondary replica.

Secondary database copies An AlwaysOn availability database copy can be constructed so that, when carrying out the secondary role, it takes client side connections for read only access to its databases. You can supply clientside connectivity to primary database replica duplicate of a given availability group by using one of followings: Unique network name You can generate a unique network name for an AlwaysOn availability group. To the extant primary replica of the AlwaysOn availability group, applications can specify this network name in connection strings. After the AlwaysOn availability group fails over, the network name directs connections to the new primary replica. You must create a network name that is unique in the

domain for each AlwaysOn availability group. As you create a network name, a virtual IP (VIP) address is assigned to the network name. Only TCP is supported for using a network name and, optionally, a F5 VIP or Virtual Address to connect to an AlwaysOn availability group. connection-strings that your applications use to connect to the databases in the AlwaysOn availability group must specify the AlwaysOn availability groupunique network name, not the host name. Applications will join directly to the current primary replica. Here are the Examples of successful connection strings from MS: Server=tcp:Mynetwork name;Database=MyDataBase;IntegratedSecurity=SSPI Server=tcp:Mynetwork name,1433;Database=MyDataBase;IntegratedSecurity=SSPI

DB mirror connection strings If an AlwaysOn availability group owns only two availability replicas and is not designed to allow read-access to the secondary replica, clients can connect to the primary replica using mirroring connection strings. This method can be useful aswhereas migrating an existing application from db mirror to an AlwaysOn availability group, as long as you limit the AlwaysOn availability group to two replica copies. Beforehand, you will want to create a VNN for the AlwaysOn availability group and update your application to use the VNN. When consuming DB mirror connection strings, the app client can use either SQL Server Native Client or .NET Framework Data Provider for SQL Server to connect to the App DB. The connection string provided by a client App must at least provide the name of one server instance, the initial partner name, to recognize the server instance that originally hosts the availability replica to which you aim to connect. The connection string can also providethe name of another server instance, the failoverpartnername, to identify the server instance that originally hosts the secondary replica copy as the failover partner name.

AlwaysOn Availability Groups PowerShell Commands


Below are the AlwaysOn Availability Groups Powershell commands.

Disable-SqlHADRService Disables the SQL HADR service on a server instance. Enable-SqlHADRService Enables the SQL HADR service on an instance of Microsoft SQL Server 2012.

New-SqlHadrEndPoint Creates a new database mirroring endpoint on a server instance. This endpoint is required for data movement between primary and secondary databases. Set-SqlHadrEndpoint Changes the properties of an existing database mirroring endpoint, such as the name, state, or authentication properties. Backup-SqlDatabase Creates a data or log backup Restore-SqlDatabase Restores a backup. Disable-SqlAvailabilityGroup Takes an availability group offline. Enable-SqlAvailabilityGroup Brings an availability group online. New-SqlAvailabilityGroup Creates a new availability group. Remove-SqlAvailabilityGroup Deletes availability group. Set-SqlAvailabilityGroup Sets the properties of an availability group; take an availability group online/offline Switch-SqlAvailabilityGroup Initiates one of the following forms of failover: A forced failover of an availability group (with possible data loss). A manual failover of an availability group. Add-SqlAvailabilityDatabase On the primary replica, adds a database to an availability group. On a secondary replica, joins a secondary database to an availability group. Remove-SqlAvailabilityDatabase On the primary replica, removes the database from the availability group. On a secondary replica, removes the local secondary database from the local secondary replica. Resume-SqlAvailabilityDatabase Resumes the data movement for a suspended availability database. Suspend-SqlAvailabilityDatabase Suspends the data movement for an availability database.

Create SQL AlwaysOn Availability Group Using Transact SQL

This example uses TransactSQL statement to make an AlwaysOn availability group named INFOTECHGUYZ for two user databases, INFOTECHGUYZDb1 and INFOTECHGUYZDb2, which reside on the local computer node. A local stand-alone server instance, HADR_INSTANCE, is specified first. This instance will host the initial primary availability replica. Another stand-alone server instance, also named HADR_INSTANCE, is specified to host the initial secondary replica. Each database mirroring endpoint uses the fully-qualified domain name of the host computer, computer_name.infotechguyz.com, and port 7022. This example configures both availability replicas so that whichever replica is performing the secondary role allows all connections for read access to its secondary databases. CREATE AVAILABILITY GROUP INFOTECHGUYZ FOR DATABASE INFOTECHGUYZDb1, INFOTECHGUYZDb2 REPLICA ON 'COMPUTER01\HADR_INSTANCE' WITH ( ENDPOINT_URL = 'TCP://aCOMPUTER01.infotechguyz.com:7022', PRIMARY_ROLE = (ALLOW_CONNECTIONS = ALL), SECONDARY_ROLE (ALLOW_CONNECTIONS = ALL) ), 'COMPUTER02\HADR_INSTANCE' WITH ( ENDPOINT_URL = 'TCP://aCOMPUTER02.infotechguyz.com:7022', PRIMARY_ROLE = (ALLOW_CONNECTIONS = ALL), SECONDARY_ROLE (ALLOW_CONNECTIONS = ALL) ); GO

New Features in SQL Server 2012

This latest release of the SQL Server presents new features and improvements that increase the power and efficiency of architects, developers, and administrators who design, develop, and maintain data storage systems.
This article will walk you through all new features that are introduced in SQL Server 2012 especially high availability. For guarding application databases in an enterprise environment from both downtimes, the main features AlwaysOn Availability Groups (AAG) feature is introduced in MS SQL Server 2012 and a number of other HA features.

Always-On Availability Groups (AAG) As for some Exchange administrators this feature is very similar to Database Availability Groups (DAG) in Exchange 2010. Configuring SQL 2012 AlwaysOn Availability Groups involves creating and constructing one or more availability groups. An availability group is a global container that defines a set user DBs (availability databases) to fail-over in case of disaster, and a set of database replicas to host multiple copies of each DB. An each group requires at least two replicas exist: the primary replica and one secondary replica. AlwaysOn Availability Groups offers a rich set of choices that increase database availability and that assist improved resource use. Below are a few feature sets of AAG:

Numerous secondary replica copies: up to four secondary db copies.

It allows control over the automatic failover process using flexible failover policy for each availability group. Provides secure, high performing transport to replicas via Encryption and compression. Other availability modes: Asynchronous-commit mode and Synchronous-commit mode Several failover modes: automatic failover, planned manual failover, and forced manual failover. For more information Through better source utilization of spare hardware permits Active secondary which increase IT efficiency and reduce cost. Provides fast application-failover via Availability group listeners. Automatic page healing for protection against page corruption. Forcing WSFC quorum

Always-On SQL Failover Cluster Failover clusters across subnets A SQL Server multisubnet failover cluster is a design where all failover cluster node is connected to a different networks or different set of networks. These networks can be in the same physical location or in phsicallydispersed . Clustering across global sites is sometimes referred to as Stretch-clusters. As there is no need for shared storage that all the nodes can access, data should be replicated among the data storage on the multiple networks. With data replication, there is further than one copy of the data available. Therefore, a multi-subnet failover cluster offers a disaster recovery solution in addition to HA. Flexible policy for cluster health detection In a SQL Server failover-cluster instance, only one node can own the cluster which is sometimes known as a single copy cluster. The client demands are served through this primary node for that failover cluster instance. In the case of a hardware failure, the group ownership is moved to another node in the failover cluster node. In this case the process is called failovering over a cluster.

Indirect checkpoints This new feature offers a database-specific substitute to automatic checkpoints, which are shaped by a server property. An indirect checkpoint implements a new checkpointing formula for the DB Engine. This offers a more accurate assurance of database recovery time in DR event or a failover than is provided by automatic-checkpoints. To guarantee that database recovery does not top allowable downtime for a given db, you can stipulate the maximum acceptable downtime for that database.

SQL Server 2012 Backup

This article will explain and walk you through backing up SQL Server 2012 databases and restore plans for SQL Server 2012 and security contemplations for SQL Server 2012 backup and restore. The SQL Server 2012 backup and restore feature provides an vital safeguard for shielding critical data stored in your SQL Server 2012 databases in case of a DR event. You want to back up your databases to preserve changes to your data on a steady basis. A well-planned backup strategy will help protect databases against loss of information by hardware and other type of failures. Routine testing and restoring your database to prepare you be SOX compliant and restore quickly if DR event were to occur. Simple Recovery Mode in SQL Server 2012 Using the simple recovery model, next each backup, the database is unprotected to potential data-loss if a disaster were to occur. The data-loss exposure rises with each update until the next backup, when data-loss disclosure returns to zero and a new cycle of data-loss exposure starts. Below is a diagram from MS that displays data-loss risk for a backup strategy that uses only full database backups.

Below is a code that emonstrates how to create a full database.


-- Back up the AdventureWorks2012 database to new-media set. BACKUP DATABASE AdventureWorks2012 TO DISK = 'E:\SQLServer2012Backup\AdventureWorksSimpleRM.bak' WITH FORMAT;GO

Full Recovery Mode in SQL Server 2012

This model backup transaction logs addition to the database.

Below demonstrates how to create a full database backup by using WITH FORMAT to overwrite any current backups and create brandnew media set.

USE master; ALTER DATABASE AdventureWorks2012 SET RECOVERY FULL; GO -- Back up the AdventureWorks2012 database to new media set (backup set 1). BACKUP DATABASE AdventureWorks2012 TO DISK = 'E:\SQLServer2012Backup\AdventureWorks2012.bak' WITH FORMAT; GO --Create a routine log backup (backup set 2). BACKUP LOG AdventureWorks2008R2 TO DISK = 'E:\SQLServer2012Backup \AdventureWorks20011.bak'; GO

Creating a maintenance plan:

1. In Object Explorer, expand Management. 2. Right-click Maintenance Plans>Maintenance Plan Wizard. 3. Follow on screen instructions to create maintenance plan.

Online Database Backup Myth Any backup process that implicitly or explicitly references data that is offline will fail. Below are a few examples:

Full database backup is setup, but one of thefilegroup of the database is offline. Since all filegroups are implicitly included in a full database backup, this process will fail. Partial backup is set to run, but a read/write filegroup is offline. Since all read/write filegroups are mandatory for a partial backup, the operation will fail. File backup of specific files are set to backup, but one of the files is offline. This process will failed as you predicted. To successfully back up the online files, you can ignore the the file that is not online from the file list and run the backup again.

Log backup will succeed even if one data files are unavailable unlike filegroups. But if any file comprises bulk-logged alterations made under the bulk-logged recovery model, all the files must be online for backup to be successful. SQL Server 2012 uses an online-backup method to permit for a database backup while the database is still online. During this backup, most of all operations are possible include INSERT, UPDATE, or DELETE statements. Moreever if you try to start a backup process while a database file is being created or deleted, the backup operation waits until the create or delete process is finished or the backup times out. During a database backup or transaction log backup below are the limitations:

ALTER DATABASE statement with either the ADD FILE or REMOVE FILE options are now allowed. You cannot shrink a database while backup is running. Most obviously you cannot create or delete databases while backup is running.

SQL Server 2012 Data Types


In SQL Server 2012, each column, local variable, expression, and parameter has a related data type. A data type is an attribute that stipulates the type of data that the object mayembrace: integer data, characters data, money data, date and time data, binary strings, and so on. SQL Server 2012 offers a set of data types that express all the types of data that may be used inSQL Server 2012. You may also express your own datatypes in TransactSQL or the .NET-Framework. User-defined types obtain their structures from the methods and operators of a class that you create by using one of the programming languages support by the .NET-Framework. When there are two expressions that have different kind of data types, collations, precision, scale, the appearances of result are determined by the:

o o o

The data type of the outcome is determined by relating the rules of data type precedence to the data types of the input expressions. The collation of the outcome is determined by the rules of collation precedence when the result data type is char, varchar, text, nchar, nvarchar, or ntext. The precision, scale, and length of the outcome depend on precision and length of the input expressions.

Integer Data Type Integers are wholesome numbers which do not contain decimals or fractions. MS SQL Server 2012 has below integer data types: Bigint Has a length of 8 bytes and stores numbers from 2^63 (-9,223,372,036,854,775,808) through 2^63-1 (9,223,372,036,854,775,807). integer or int Has a length of 4 bytes, and stores numbers from -2,147,483,648 through 2,147,483,647. Smallint Has a length of 2 bytes, and stores numbers from -32,768 through 32,767. Tinyint Has a length of 1 byte, and stores numbers from 0 through 255. Integer objects and languages can be used with any calculated operations. Any fractions produced by these processes are truncated, not rounded. For example, SELECT 7/3 returns a value of 2, not the value 3, which would return if the fractional result were rounded.The integer data types are the single ones that can be used with the IDENTITY property, which is anroutinely incrementing number. The IDENTITY property is

typically used to automatically generate UID numbers or primary keys. With Integer data, no need toto be enclosed in single quotes like character data type. Binary Data Type The binary data types store strings of bits and although character data is understood based on the SQL Server 2012
code, binary data is simply a stream of bits. This typeof data can store a max of 8000 bytes. Varbinary on the other hand can store a max of 2^31 bytes. Binary factors have a leading 0x which is followed by the hex illustration of the bit pattern. As an example, 0x2A stipulates the hexvalue of 2A, which is equal to a decimal value of 42 or a one-byte bit pattern of 00101010.Use binary data type when storing hex values such SSN, social security numbers, SIDs and GUIDs.

Below example stores a SID and hexadecimal verbatim: USE AdventureWorks2012; GO CREATE TABLE MyCcustomerTable ( user_loginvarbinary(85) DEFAULT SUSER_SID() ,data_valuevarbinary(1) ); GOINSERT MyCustomerTable (data_value) VALUES (0x4F); GO Att

Char and Varchar Data Type


These-- char and varchar data type store data poised of the following:

o o o

Uppercase and lowercase strings such as a, b, and C.

Special characters like as the "at" sign (@),(&), and (!). Numbers such as 1, 2, and 3.

The char or varchar data type can be a single character, or it can be a string with a max of 8000 characters for char data. It also allow up to 2^31 characters for varchar data. varchar data can be of a stated maximum length of characters, as an example, varchar(6) indicates that this data type can store a maximum of six characters; or it can be of the form varchar(max), this increases the max number of chars that can be kept by this data type to 2^31. Each char and varchar data value has a collection. This Collationsdescribe attributes such as the bit patterns used to characterize each character, comparison rules, and sensitivity to case or accenting. All database possess a default collation which is set during the installation . When a column is defined, or a constant stated, they are allocated the default collation of the database if not you assign a specific collation byrunning the COLLATE

clause. When two char or varchar values having dissimilar collations are joint or compared, collation precedence rules define which collation is used for the operation. These Character constants must be in single quotes (') or double quotes ("). Hem in a character constant in single quotation marks is highly recommended. Enclosing a character constant within in double quotes is occasionally not allowed when the QUOTED IDENTIFIER option is set to ON. Below example sets a character variable to a value:
DECLARE @MyCharVarCHAR(25) SET @MyCharVar = 'Ricardo Adocicados'

When using single quotation marks to delimit a character constant that contains an embedded single quotation mark, use two single quotation marks to represent the embedded single quotation mark. For example:
SET @MyCharVar = 'O''Leary'

If the data to be stored is longer than the number of characters allowed, the data is truncated. For example, if a column is defined as char(10) and the value "This is a really long character string" is stored into the column, SQL Server 2012 truncates the character string to "This is a ".

Data and Time Data Type String literal formats affect the performance of data in applications to users but not the fundamental integer storage format in SQL Server 2012. SQL Server 2012 might take a date value in a string literal format, input by an application or user for storage or to a date function, as different dates. The interpretation be influenced by on the combination of string literal format, data type, and runtime SET DATEFORMAT, and default language option and SET LANGUAGE settings.Some of the string literal formats are not all affected by these settings. Consider using a format that doesnt always depend on these settings, unless you are sure that the settings are correct for the format. Transact-SQL that uses string literal formats, dependent on system settings.The ydm date format is not allowed for the date, datetime2 and datetimeoffset types. A run time error will be raised since this is not supported. The following lists different date and time string formats. MS recommend that you use date-time formats that are not DATEFORMAT reliant on and are multilanguage. The ISO 8601 formats, '1998-02-23T14:23:05' and '1998-02-23T14:23:05-08:00' are the only formats that are an international standard. They are not DATEFORMAT or default login language dependent and are multilanguage.

Date-time Format type Format part example

Can combine with other formats Yes

DATEFORMAT Multilanguage dependent

Date

Un-separated ISO 8601

'19980223'

No

Yes

Date

Numeric

'02/23/1998'

Yes

Yes

No (DATEFORMAT)

Date

ISO 8601 Numeric

'1998-02-23'

Yes

No

No

Date

Alphabetical

'23 February 1998'

Yes

No

No (month or short month)

Date

ODBC date

{d '1998-0223'}

No

No

Yes

Time

ISO 8601 Time

'14:23:05' '10:00:00.123456' {t '14:23:05'}

Yes

No

Yes

Time

ODBC time

No

No No

Yes Yes

Date-time ODBC datetime Date-time ISO 8601

{ts '1998-02-23 No 14:23:05'} '1998-0223T14:23:05' '1998-0223T14:23:05 08:00' No

No

Yes date, datetime2, datetimeoffset.

Date-time ANSI SQL Standard

'1998-02-23

No

No (datetime2,

Yes date, datetime2,

14:23:05' '1998-02-23 14:23:05 08:00' Date-time Combination of date and time


'19980223 14:23:05'

datetimeoffset) Yes (datetime)

datetimeoffset.

No

Yes (date part)

No

'02/23/1998 2:23:05 PM' '1998-02-23 10:00:00.123' '23 Feb 1998 14:23:05'

TimeZone TimeZone Format

'+12:00' '01:00' '-08:00' 'Z'

Yes

No

Yes

Example of SET LANGUAGE and SET DATEFORMAT settings. DECLARE @Today date = '1/1/2012'; DECLARE @MyTime time = '1:30:00'; DECLARE @MyDatetimeoffsetdatetimeoffset = '1/1/20121:30:00 -5:00'; SET LANGUAGE Italian -- Returns: Changed language setting to Italiano. SELECT DATENAME(month, @Today) AS 'Month Name';

-- Returns: dicembre SELECT CONVERT(VARCHAR(30), @MyDatetimeoffset) AS 'DATETIMEOFFSET'; -- Returns: dic 1 2003 12:30PM -05:00 SELECT DATENAME(hour, @MyTime) As 'Hour Name'; -- Returns: 12

SET LANGUAGE us_english; -- Returns: Changed language setting to us_english. SELECT DATENAME(month, @Today) AS 'Month Name'; -- Returns: December SELECT CONVERT(VARCHAR(30), @MyDatetimeoffset) AS 'DATETIMEOFFSET'; -- Returns: Dec 1 2003 12:30PM -05:00 SELECT DATENAME(hour, @MyTime) As 'Hour Name'; -- Returns: 12 GO -- Set date format to month, day, year. SET DATEFORMAT mdy; GO DECLARE @datevar date = '12/31/1998'; SELECT @datevar AS DateVar; -- Returns: 1998-12-31 GO

-- Set date format to year, day, month. SET DATEFORMAT ydm; GO DECLARE @datevardatetimeoffset = '1998/31/12 1:30:00 -05:00'; SELECT @datevar AS DateVar; -- Returns: Msg 241, Conversion failed when converting -- date and/or time from character string. GO -- Set date format to year, month, day. SET DATEFORMAT ymd; GO DECLARE @datevar date = '12/31/1998'; SELECT @datevar AS DateVar; -- Returns: 1998-12-31 GO

Currency Data Type Currency or monetary data type does not need to be enclosed in single quotes. It is vital to remember that while you may specify currency values lead by a currency symbol, SQL Server 2012 does not store any currency info associated with the symbol, it only stores the numeric value. As an example, to assign a value of 900 Dollars to a variable, you can do the following:
DECLARE @dollars AS money SET @dollars = $900 SELECT @dollars

The value returned is 100.0000, without a currency symbol.

If an object is defined as currency, it can contain a maximum of 19 digits, 4 of which can be to the right of the decimal. The object uses 8 bytes to store the data. The money data type therefore has a precision of 19, a scale of 4, and a length of 8. money and smallmoney are limited to four decimal points. Use the decimal data type if more decimal points are required. Use a period to distinct partial monetary units, like cents, from whole monetary units. Commafilters are not allowed in money or smallmoney constants, though the display format of these data types embraces comma separators. You can stipulate the comma separators only in character strings explicitly cast to money or smallmoney. For example:
USE sqltestdb; GO CREATE TABLE TestMoney (cola INT PRIMARY KEY, colb MONEY); GO SET NOCOUNT ON; GO

-- The following three INSERT statements work. INSERT INTO TestMoney VALUES (1, $123.45); GO INSERT INTO TestMoney VALUES (2, $123123.45); GO INSERT INTO TestMoney VALUES (3, CAST('$344,323.45' AS MONEY) ); GO

-- This INSERT statement gets an error because of the comma -- separator in the money string. INSERT INTO TestMoney VALUES (3, $455,123.45); GO

SET NOCOUNT OFF; GO SELECT * FROM TestMoney; GO

Data Conversions

SQL Server 2012 Installation Guide


We will start with list the minimum hardware and software requirements to SQL Server 2012. For both x64 and x86 editions, MS suggests the use of NTFS file system, you must install Powershell 2.0, both .NET 3.5 SP1 and .NET 4.0 is required. The hardware requirements are:

Supported OS: Server 2008 R2 SP1, Windows 7 SP1, Server 2008 SP2, and Vista SP2. Processor: o Minimum for x64 installations: AMD Opteron, AMD Athlon 64, Intel Xeon with Intel EM64T support, Intel Pentium IV with EM64T support. Processor Speed: 1.4 GHz o Minimum for x86 installations: Pentium III compatible or higher. Processor Speed: 1.0 GHz Memory: Minimum: 1 GB

SQL Server 2012 Express

Supported OS: Server 2008 R2 SP1, Server 2008 SP2, Windows 7 SP1, and Vista SP2. Processor: o Minimum for x64 installations: AMD Opteron, AMD Athlon 64, Intel Xeon with Intel EM64T support, Intel Pentium IV with EM64T support. Processor Speed: 1.4 GHz o Minimum for x86 installations: Pentium III compatible or higher. Processor Speed: 1.0 GHz Memory: Minimum: 512 MB

WOW64 (Windows x86 on Windows x64) is a piece of x64 editions of Windows that enables x86apps to run natively in x86 mode. Apps function in x86 mode, even though the underlying operating system is x64 operating system. WOW64 is supported only for stand-alone instances of SQL Server. WOW64 is not supported for SQL Server failover cluster installations For SQL Server x64 edition installations on x64 supported OS, Management Tools are supported in WOW64. On a supported x64 operating system, SQL Server x86 edition installations can be installed to the WOW64 x86 subsystem of ax64 server. SQL Server editions that are supported on Server 2008 R2 x64x64 Standard are also supported on Windows Small Business Server x64x64. SQL Server 2012 is now supported on Windows 2008 R2 SP1 server core operating system. Server core functionality is available on the following Server 2008 R2 editions:

Server 2008 R2 SP1 x64x64 Datacenter Server 2008 R2 SP1 x64x64 Enterprise Server 2008 R2 SP1 x64x64 Standard Server 2008 R2 SP1 x64x64 Web

Step-by-Step Installation
To install SQL Server 2012

1. Double-click click Setup.exe from ISO. The Installation Wizard runs the SQL Server Installation Center. new installation of SQL Server is created by, clicking Installation in the left-hand hand area, and then click New SQL Server stand-alone stand installation or add features to an existing installation. 2. The System Config Checker runs a detection operation on your compute computer. r. To stay, click OK. You can view the specifics on the screen by clicking Show Details, or as an HTML report by clicking View detailed report. 3. On the Setup Support Files page, click Install.The System Config Checker runs a discovery operation on your com computer. To continue, click OK. You can view the details on the screen by clicking Show Details, or as an HTML report by clicking View detailed report. 4. You can specify the language for your instance of SQL Server if you are installing on a localized operating g system and the installation media includes language packs for both English and the language corresponding to the operating system. clickNext and continue. 5. On the Product Key page, select an option to indicate whether you are installing a free edition of SQL Server, or a production version of the product that has a PID key. To continue, click Next. 6. On the License Terms page, review the license agreement and, if you agree, select the I accept the license terms check box, and then click Next. To help improve SQL Server, you can also enable the feature usage option and send reports to MS. 7. On the Product Updates page, the latest available SQL Server product updates are displayed. If you don't want to include the updates, clear the Include SQL Server product updates check box. If no product updates are discovered, SQL Server Setup does not display this page and auto advances to the Install Setup Files page. 8. On the Install Setup files page, Setup provides the progress of downloading, extracting, and installing the he Setup files. If an update for SQL Server Setup is found, and is stated to be included, that update will also be installed. 9. The System Config Checker verifies the system state of your computer before Setup continues. 10. On the Setup Role page, select SQL Server Feature Installation, and then click Next to continue to the Feature Selection page.

11. On the Feature Selection page, select the components for your installation. A description for each component group appears in the Feature description pane after you select the feature name. You can also specify a custom directory for shared components by using the field at the bottom of the Feature Selection page. To change the installation path for shared components, either update the path in the field at the bottom of the dialog box, or click Browse to move to an installation directory. The default installation path is C:\Program Files\MS SQL Server\110\. The path stated for the shared components must be an absolute path. The folder must not be compressed or encrypted. Mapped drives are not supported. If you are installing SQL Server on a 64-bit Operating System, you will see the following options:
o o

Shared feature directory Shared feature directory (x86)

The path stated for each of the above options must be different. 12. On the Installation Rules page, Setup verifies the systemstate of your computer before Setup continues. On the Instance Config page, specify whether to install a default instance or a named instance. 1. Instance ID By default, the instance name is used as the Instance ID. This is used to identify installation directories and registry keys for your instance of SQL Server. This is the case for default instances and named instances. For a default instance, the instance name and instance ID would be MSSQLSERVER. To use a non-default instance ID, specify a different value for Instance ID text box. 2. Instance root directory By default, the instance root directory is D:\Program Files\MS SQL Server\110\. To specify a non-default root directory, use the field provided, or click Browse to locate an installation folder. All SQL Server service packs and upgrades will apply to every component of an instance of SQL Server. 3. Installed instances The grid shows instances of SQL Server that are on the computer where Setup is running. If a default instance is already installed on the computer, you must install a named instance of SQL Server 2012. The Disk Space Requirements page calculates the required disk space for the features that you specify. Then it compares the required space to the available disk space. Work flow for the rest of this topic depends on the features that you have stated for your installation. You might not see all the pages, depending on your selections. Use the Server Config Service Accounts page to specify login accounts for SQL Server services. The actual services that are configured on this page depend on the

features that you selected to install. You can assign the same login account to all SQL Server services, or you can configure each service account individually. You can also specify whether services start automatically, are started manually, or are disabled. MS recommends that you configure service accounts individually to provide least privileges for each service, where SQL Server services are granted the minimum permissions they have to have to complete their tasks. To specify the same logon account for all service accounts in this instance of SQL Server, provide credentials in the fields at the bottom of the page. When you are finished specifying login information for SQL Server services, click Next.Use the Server Config Collation page to specify non-default collations for the Database Engine and Analysis Services. Use the Database Engine Config Account Provisioning page to specify the following:
o

Security Mode Select Windows Authentication or Mixed Mode Authentication for your instance of SQL Server. If you select Mixed Mode Authentication, you must provide a strong password for the built-in SQL Server system administrator account. After a device establishes a successful connection to SQL Server, the security mechanism is the same for both Windows Authentication and Mixed Mode. SQL Server Administrators You must specify at least one system administrator for the instance of SQL Server. To add the account under which SQL Server Setup is running, click Add Current User. To add or remove accounts from the list of system administrators, click Add or Remove, and then edit the list of users, groups, or computers that will have administrator privileges for the instance of SQL Server. When you are finished editing the list, click OK. Verify the list of administrators in the Config dialog box. When the list is complete, click Next.

Use the Database Engine Config - Data Directories page to specify non-default installation directories. To install to default directories, click Next. Use the Database Engine Config - FILESTREAM page to enable FILESTREAM for your instance of SQL Server.

Use the Analysis Services Config Account Provisioning page to specify the server mode and the users or accounts that will have administrator permissions for Analysis Services. Server mode regulates which memory and storage subsystems are cast-off on the server. Different solution types run in different server modes. If you plan to run multidimensional cube databases on the server, choose the default option, Multidimensional and Data Mining server mode. Regarding administrator permissions, you must specify at least one system

administrator for Analysis Services. To add the account under which SQL Server Setup is running, click Add Current User. To add or remove accounts from the list of system administrators, click Add or Remove, and then edit the list of users, groups, or computers that will have administrator privileges for Analysis Services. When you are finished editing the list, click OK. Verify the list of administrators in the Config dialog box. When the list is complete, click Next.

Use the Analysis Services Config Data Directories page to specify non-default installation directories. To install to default directories, click Next. After you choose an option, click Next to continue.

Use the Distributed Replay Controller Config page to specify the users you want to grant administrative permissions to for the Distributed Replay controller service. Users that have administrative permissions will have unlimited access to the Distributed Replay controller service. Click the Add Current User button to add the users to whom you want to grant access permissions for the Distributed Replay controller service. Click the Add button to add access permissions for the Distributed Replay controller service. Click the Remove button to remove access permissions from the Distributed Replay controller service.

To continue, click Next.

Use the Distributed Replay Client Config page to specify the users you want to grant administrative permissions to for the Distributed Replay client service. Users that have administrative permissions will have unlimited access to the Distributed Replay client service.

Specify the Working Directory for the Distributed Replay client service. The default working directory is <drive letter>:\Program Files\MS SQL Server\DReplayClient\WorkingDir\. Specify the Result Directory for the Distributed Replay client service. The default result directory is <drive letter>:\Program Files\MS SQL Server\DReplayClient\ResultDir\. To continue, click Next.

The System Config Checker will run one more set of rules to validate your computer Config with the SQL Server features that you have stated. The Ready to Install page shows a tree view of installation options that were stated during Setup. On this page, Setup indicates whether the Product Update feature is enabled or disabled and the final update version.

To continue, click Install. SQL Server Setup will first install the required prerequisites for the selected features followed by the feature installation.

During installation, the Installation Progress page provides status so that you can monitor installation progress as Setup continues. After installation, the Complete page provides a link to the summary log file for the installation and other important notes. To complete the SQL Server installation process, click Close. Restart the computer end of installation.

SQL Server 2012 Requirements


This article describes the Minimum requirement hardware and software requirements to run and successfully install SQL Server 2012. Below are the requirements for both x86 and x64 editions of MSSQL Server 2012:
o o o o

MSSQL Server 2012must run NTFS file system. But MSSQL Server 2012 will allow upgrades from FAT32 File system. MS SQL Server 2012 CANNOT be installed on read-only, mapped, nor compressed drives. PowerShell 2 is a prerequisite. .NET 3.5 SP1 is a prerequisite for MSSQL Server 2012for Database Engine, Reporting Services, Data Quality Services, Master Data Services, Replication, or SQL Server Management Studio. This must be installed from Server 2008 features or install it manually. The newer .NET 4.0 is a prerequisite for MSSQL Server 2012. The installer will install .NET 4.0 during the setup.

OS and Software Requirements The following requirements apply to all MSSQL Server 2012 installations: Software Framework Requirement
o o o o

.NET Framework 4 .NET Framework 3.5 SP1 SQL Native Client SQL Setup support files

Network

Network related software requirements for the x64 versions of MSSQL Server 2012 are the same

Related

as the requirements for the x86 versions.Supported OS have builtin network software. Standalone named and default instances support the following network protocols:

o o o o

Shared memory Named Pipes TCP/IP VIA

Virtualization

MSSQL Server 2012 is supported in VM environments running on the Hyper-V role in Server 2008 SP2 Standard Enterprise and Datacenter editions, VMWare support is not announced at the moment.

Here are recommended practices when using VMs:


o o

We highly recommend that MSSQL Server 2012 is shut down manually prior to shutting down the VM. Guest failover-clustering is supported in MSSQL Server 2012.

HardDisk

Disk space requirements will vary with the MSSQL Server 2012 components you install.

MediaDrive

A CD or DVD for physical installation disc. ISO files can also be extracted using Winrar.

Display

VGA resolution at least 1,024x768 or higher.

Hardware Requirements:
o o

Supported OS: Server 2008 R2 SP1, Windows 7 SP1, Server 2008 SP2, and Windows Vista SP2. Processor: Minimum requirement for x64 installations: AMD Opteron, AMD Athlon 64, Intel Xeon with Intel EM64T support, Intel Pentium IV with EM64T support. Processor Speed: 1.4 GHz Minimum requirement for x86 installations: Pentium III compatible or higher. Processor Speed: 1.0 GHz Memory: Minimum requirement: 1 GB

MSSQL Server 2012 Express

o o

Supported OS: Server 2008 R2 SP1, Server 2008 SP2, Windows 7 SP1, and Windows Vista SP2. Processor: Minimum requirement for x64 installations: AMD Opteron, AMD Athlon 64, Intel Xeon with Intel EM64T support, Intel Pentium IV with EM64T support. Processor Speed: 1.4 GHz Minimum requirement for x86 installations: Pentium III compatible or higher. Processor Speed: 1.0 GHz Memory: Minimum requirement: 512 MB

WOW64 (Windows x86 on Windows x64) is a piece of x64 editions of Windows that enables x86apps to run natively in x86 mode. Apps function in x86 mode, even when the underlying operating system is x64 operating system. WOW64 is supported only for stand-alone instances of SQL Server. WOW64 is not supported for SQL Server failover cluster installations For SQL Server x64 edition installations on x64 supported OS, Management Tools are supported in WOW64. For more information about supported OS, select an edition of MSSQL Server 2012 from the sections below. On a supported x64 operating system, SQL Server x86 edition installations can be installed to the WOW64 x86 subsystem of ax64 server. SQL Server editions that are supported on Server 2008 R2 x64x64 Standard are also supported on Windows Small Business Server x64x64. MSSQL Server 2012 is now supported on Windows 2008 R2 SP1 server core operating system. Server core functionality is available on the following Server 2008 R2 editions:
o o o o

Server 2008 R2 SP1 x64x64 Datacenter Server 2008 R2 SP1 x64x64 Enterprise Server 2008 R2 SP1 x64x64 Standard Server 2008 R2 SP1 x64x64 Web

SQL Server 2012 Failover Cluster Installation Guide


This article will walk you through SQL Server 2012 failover cluster installation. First, lets start with the requirements.

Basic OS requirements

Windows Powershell 2.0

.Net framework 3.5 SP1 .Net framework 4 Ensure Antivirus software is compatible and proper exclusions are set. Remove disabled NICs by running set devmgr_Show_Nonpersistent_Devices=1

Basic Cluster requirements


Do not use special characters in the cluster name Confirm all cluster members are similar hardware and ensure disk resource is online and same drive letters. Ensure SQL cluster service account is not a local administrator on sql nodes.

Installing SQL Server 2012 Failover Cluster 1. 2. 3. 4. 5. 6. 7. Copy SQL Server 2012 files locally. Ensure all above requirements are met. Note: Setup uses Windows Installer version 4.5. When prompted, install setup support files Choose desire language when asked. Choose Add node Follow on screen instructions. When prompted, choose desired components for your install; note you may add additional components later. 8. Enter the instance name of the SQL Instance. This is used to indenitfy the SQL Installation instance since multiple SQL instances can exist one server.

Adding a node member to existing 2012 Failover Cluster 1. 2. 3. 4. 5. Copy SQL Server 2012 files locally. Ensure all above requirements are met. Note: Setup uses Windows Installer version 4.5. Choose Installation > Add node to a SQL server failover cluster. When prompted, install setup support files Follow on screen instructions.

Removing a node member from 2012 Failover Cluster 1. Copy SQL Server 2012 files locally and launch setup.exe 2. After launching setup.exe, choose Maintenance > Remove node from a SQL server failover cluster.

3. Follow on screen instructions.

Link Server in SQL Server 2012


To run or call commands against database data sources outside of its instance, you must configure a linked server. Usually, to connect to external data sources such as Oracle, linked server needs to be configured to allow the database engine to run the SQL statement. External data sources such as Oracle, MS Access and Excel can be configured as linked servers. This feature also allows DBAs to load balance queries, commands, and updates among different sources in the organization. You can use SQL management studio and Transact SQL to configure linked servers. Link server consists of OLE DB provider and OLE DB data source. Its a Dynamic Link Library that communicates with a particular data source. Usually, queries are distributed when receiving requested from client applications. Configuring a Linked Server via SQL Management studio: 1. Launch SQL Management Studio, open Object explorer, under server objects, Rightclick Linked Servers and then click New Linked Server. 2. Type in the SQL Server instance that you wish to link to. 3. Select SQL Server to dictate that the linked server is a different instance. 4. Configure security settings and click OK

Configuring a Linked Server via TransactSQL: 1. Launch query editor, run below transactSQL command. USE [master] GO EXEC master.dbo.sp_addlinkedserver @server = N'SQL01\instance1', @srvproduct=N'SQL Server' ; GO

2. Test the linked server by running below command. SELECT name FROM [SQL01\instance1].master.sys.sysdatabases ; GO

Configuring SQL Server 2012 Collation


Collations allows for rule sorting, case sorting, and accent sensitivity of your data. Collation is very important and you must take it into consideration when installing a new SQL 2012 server, mounting databases and restoring database from backup. Locale requirements may be different for each database/server. Each character in data set is specified by the collation. SQL Server 2012 allows storing objects that have different collations within a database. Various collation settings can have a different effect on transactSQL queries. MS recommends that you use a single collation within your company. Windows collations dictate set of rule for saving character data based on windows locale. It specifies how sorting is applied and which alphabet or language is used. Note that string comparisons for sorting in Unicode and non-unicode is compatible. Binary collations sort depending on the order of coded values that are set by the data and locale type. Data comparisons are based upon the code points that are in set ansi code page for non-uncode type data. Collations can be configured at three different levels: Server Collations The collation set during the installation automatically set the server collation. Keep in mind that Unicode-only collation is not supported at the server level, hence you cannot select it during installation. If you need to change the server collation installation, you must export all current databases and rebuild the master db. An easier route may be to set the collation at the DB level as explained below. Database Collations You may override the server collations by using the collate option when running create database sql statement. This is helpful if your new database requires a different collation than the server default. Note that alter database allow you to change collations on newly created databases but not on the system database. Column and Expression Collations Collations can also be set at the column level by using the COLLATE clause. Expression collations are set dynamically when sql statement is run and returned results are affected.

How to Change Server Collation 1. Export all of your database and unmounts all use databases.

2. Rerun setup and rebuild the master database by using below command: Setup /ACTION=REBUILDDATABASE /INSTANCENAME=Instance /SQLSYSADMINACCOUNTS=accounts /[ SAPWD= Password ] /SQLCOLLATION=Collation 3. Reimport all your data.

How to Change Database Collation 1. Run below command to set collation for newly created database: CREATE DATABASE database_name COLLATE collation_name 2. Run below command to set collation for existing database: ALTER DATABASE database_name COLLATE collation_name

Configuring SQL Server 2012 Database Server


SQL 2012 is a highly scalable database engine and allows for customizations to fit your needs. Each named instance can be configured to meet your application requirements including trigger recursion, auditing, and resource usage. Customizing DB instance in SQL Server 2012 allows DBAs to meet SLA requirement set by an organization. It is recommended that you configure the database instance prior to placing it production. Below are the special configurations, such as network connection and others that can affect database performance. Two main tools we will be using are SQL Server Management Studio and SQL server configuration manager.

General server properties This can be viewed by choosing properties of the server from SQL management studio. Configure server connection properties SQL Management studio > rightclick on server > properties. Click on Connections in SQL server properties dialog box. On Connections page, set desire remote server connections. You must restart the server for this to take effect. Affinity Mask Configuration OS such as Server 2003 move worker threads between two or more processors for multitask jobs. To allow use additional processors, SQL Management studio > rightclick on server > properties. Choose Processors. In Enable Processors , clear the automatically set processor affinity mask for all processors check box. This will allow you to configure CPU affinity. C2 Audit Tracing This mode allows the server to audit success and fail attempts to objects which can be

used to investigate security breaches. To set the c2 audit mode, SQL Management studio > rightclick on server > properties. Check enable c2 audit tracing under security page. Enable or Disable Backup Compression To configure this option, SQL Management studio > rightclick on server > properties. Under Database settings > Backup and restore, check compress backup Cursor Threshold Option configuration Use this setting to state the number of row in the cursor set. The query optimizer guess that number of returned rows is greater than this threshold. To configure this option, SQL Management studio > rightclick on server > properties. Click Advanced, change the Cursor threshold option under Miscellaneous section. Default Full-Text Language setting This dictate the default language for fulltext indexed columns. You may need to change this since this option is set to default language of the server. To change this vaule, To configure this option, SQL Management studio > rightclick on server > properties. Click Advanced, configure default full text language Default Language configuration To configure this option, SQL Management studio > rightclick on server > properties. Click on Misc server settings. Choose desired language. Fixed Fill Factor Option This option allows admins to control how SQL 2012 make each page when creating a new index using current data. To configure this setting, go to SQL Management studio > Right-click on server > Properties. Choose Database settings, then set the default index fill factor. Locks option configuration Use this to specify the max number of available locks by limiting the amount of memory SQL 2012 uses. To configure this setting, go to SQL Management studio > Right-click on server > Properties. Click Advanced. Then configure locks option under parallelism. Minimum Query Memory Configuration This setting specifies the minimum amount of memory that will be set for execution of a query. To configure this option, go to SQL Management studio > Right-click on server > Properties. Click Memory > Minimum memory per query. Set Backup media Retention This function provides a default retention period for backups preventing backups from being overwritten. The length of time to retain backups does not need to be specified when configuring this setting. By default this is set to 0 days. To configure this setting, go to SQL Management studio > Right-click on server > Properties. Choose Database settings. In backup/restore section, configure the default backup media retention box. Allow Triggers to Fire Others Option This option controls nested triggers, whether if a trigger can launch another trigger to be initiated. Nested triggers can flow down up to 32 leaves. To configure this setting, go to SQL Management studio > Right-click on server > Properties. Click Advanced. Configure Allow Triggers to Fire Others. Boost SQL Server priority option This option allows you to control the process priority on Server 2008 and R2. Setting this option to True will change the priority base to 13. . To configure this setting, go to SQL

Management studio > Right-click on server > properties. Choose Processors..Under Threads section, check Boost SQL Server priority. Remote Server Access option This options allows stored procedures to be executed remotely from remote clients. To configure this setting, go to SQL Management studio > Right-click on server > Properties. Choose Connections, under remote server connections section, configure allow remote connections to this server. Remote Login Timeout option This option allows you to set the wait time before failed log in (due to network connectivity) attempts. To configure this setting, go to SQL Management studio > Rightclick on server > properties. Click Advanced. Configure remote login timeout under Network section. Network Packet Size option By default, SQL Server 2012 packet size is 4KB. This can be changed if needed or recommended by your network administrator. To configure this setting, go to SQL Management studio > Right-click on server > Properties. Click Advanced. Configure Network Packet Size under Network section. Max number of concurrent connections option By default, there is no limit on user connections. Often times, this can be a security risk depending on your policies. This option allows you to set the max number of simultaneous user connections to the SQL Server 2012. To configure this setting, go to SQL Management studio > Right-click on server > Properties. Click connections, set the Max number of concurrent connections. Remote Query time out option This allows admins to specify the time out of remote sql queries. The default is set to 10 minutes and this can be changed to fit your needs. To configure this setting, go to SQL Management studio > Right-click on server > Properties. Click connections, set the Remote Query time out option under remote server connections.

Contained Databases in SQL Server 2012

When a database or application is migrated from on SQL instance to another server, the current database model is left behind. Contained database in SQL Server 2012 retain all information and objects in the database. A few examples are functions, tables, schemas and types. Settings such as linked servers, sql agent jobs and other application scope objects are also kept within the database. SQL 2012 contained database includes all mentioned settings and metadata required so it doesnt have dependencies on the current database instance. This allows for application and database portability. This allows database administrators to simply migrate databases to another SQL server without worrying.

Managing SQL Server 2012 via PowerShell

PowerShell is the latest scripting language designed for windows administrators, system administrators and database administrators. SQL Server 2012 allows administrators to perform management and daily tasks via PowerShell. Administrator can also script SQL Server 2012 tasks with PowerShell. Admins can easily build complicated scripts with powershell since it allows for more roust logic compare to transactSQL. SQL Server 2012 PowerShell module loads a list of cmdlets that allows administrator of SQL Server 2012. This addin sqlps enable your powershell console to run specific SQL Server cmdlets, run powershell scripts and manage SQL Server objects. To load the SQL Server 2012 PowerShell add-in / module: 1. Open PowerShell console. 2. Run Set-ExecutionPolicy unrestricted 3. Import-module sqlps If you wish to use SQL Objects and SMO assemblies, you need to load them manually. Use below PowerShell script to load them. #################SCRIPT STARTS#################
$sql2011registry="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.Sq lServer.Management.PowerShell.sqlps" $item = Get-ItemProperty $sql2011registry $powershelldir = [System.IO.Path]::GetDirectoryName($item.Path) $smoarray = "Microsoft.SqlServer.Management.Common", "Microsoft.SqlServer.Dmf ", "Microsoft.SqlServer.Smo", "Microsoft.SqlServer.Instapi ", "Microsoft.SqlServer.SqlWmiManagement ", "Microsoft.SqlServer.SmoExtended ", "Microsoft.SqlServer.ConnectionInfo ", "Microsoft.SqlServer.SqlTDiagM ",

"Microsoft.SqlServer.SString ", "Microsoft.SqlServer.Management.Sdk.Sfc ", "Microsoft.SqlServer.SqlEnum ", "Microsoft.SqlServer.RegSvrEnum ", "Microsoft.SqlServer.WmiEnum ", "Microsoft.SqlServer.Management.DacEnum", "Microsoft.SqlServer.ServiceBrokerEnum ", "Microsoft.SqlServer.Management.Collector ", "Microsoft.SqlServer.Management.CollectorEnum", "Microsoft.SqlServer.ConnectionInfoExtended ", "Microsoft.SqlServer.Management.RegisteredServers ", "Microsoft.SqlServer.Management.Dac", "Microsoft.SqlServer.Management.Utility" foreach ($assembly in $smoarray)

{
$assembly = [Reflection.Assembly]::LoadWithPartialName($assembly)

}
Push-Location cd $powershelldir update-FormatData -prependpath SQLProvider.Format.ps1xml Pop-Location

#################SCRIPT ENDS################# Now that all the prep work are done, you can use Invoke-SQLcmd query select * from table to run your SQL queries. For full list of commands, run get-command. lets start talking about interactions between management studio and powershell. Note that you can run Powershell directly from SQL Server 2012 management studio. This is done by simply rightclicking the database of your choice and choose Start PowerShell. This will set the

selected database as the default path. When you run powershell directly from management studio, sqlps module is loaded automatically and no need to perform prep work described earlier. Prep work mentioned about is only need when running SQL commands from plain old powershell and running SQL 2011 PowerShell Scripts.

SQL Server 2012 Agent and PowerShell You may schedule sql agent tasks using powershell scripts by including the ps1 script in your jobs. Basically you are launching powershell, loading the sqlps module and running the sql cmdlets. To do this: 1. Open SQL Server Management Studio 2. Open SQL Server Agent Node. 3. In SQL Server 2012 agent, create a new job and open the properties, go to steps, then choose New 4. Enter the name of the job, choose PowerShell as the type list. 5. In the Command pane, paste the powershell script content. 6. Follow on screen instructions.

Working with SQL Management Object Assemblies SQL server Powershell allows browsing of SQL server objects as how you would browse the file system, objects can be located by path and perform actions by using its methods. Below are list of paths:

SQLSERVER:\SQL
Database objects, such as tables, views, and stored procedures.

SQLSERVER:\SQLPolicy Policy-based management objects, such as policies and facets.


SQLSERVER:\SQLRegistration

Registered server objects, such as server groups and registered servers.


SQLSERVER:\Utility

Utility objects, such as managed instances of the Database Engine.


SQLSERVER:\DAC

Data-tier application objects such as DAC packages, and operations such as deploying a DAC SQLSERVER:\DataCollection Data collector objects, such as collection sets and configuration stores.

SQL Server 2012 Database Mail Explained

Database mail in SQL Server 2012 allows database administrators to send emails directly from SQL Server. You can create applications that send emails to users directly. This is done natively without using any additional SMTP add ins and SQL Server 2012 database mail even supports high availability by allowing more than one mail server to be setup. Within SQL this is done by running the sp_send_dbmail to send an email message programmatically. You may also change the attachment size by running the sysmail_configure_sp procedure. This will also allow dbas configure allowed and disallowed file extensions. Database mail configuration for SQL Server 2012 is saved in msdb database. Also, you may use SQL agent to send mail using database mail.

Managing Database Mail accounts and Profile within SQL Server 2012 To send an email message to a SMTP server, your database mail account must have all necessary configuration data. At minimal you must have one SMTP server configured for an account. A lot environment will allow you to send emails internally without authenticating. In some case, it will require authentication if you want to relay through a SMTP server. You can use Anonymous Authentication, if your SMTP mail server doesnt require any authentication. Basic Authentication is used for Database mail that uses a simple username / password. At last, Windows Authentication allows authentication via a windows account. This can be a local account or active directory account. All the account configuration are stored in msdb as mentioned earlier. This includes:

Account name Account description Accounts email address Accounts displayname Email server host name SMTP port number, default is 25 SSL configuration Authentication information mentioned earlier.

In SQL Server 2012, Profile is essentially a group of database mail accounts. This allows database administrators and system administrators to build redundant and highly available database mail infrastructure. If one of the SMTP server is down, SQL Server will automatically failover and try to send the email to an alternate SMTP server within the database mail profile.

How to Create a Database Mail Account Prior to creating a SQL Server 2012 database mail account, you must have the name of your SMTP server, port number and credentials. Note that this can be obtained from your system administrator, Exchange administrator or IT manager. In some cases you will not need to authenticate it the mail server. By default port number is usually 25.

Open SQL Management Studio. Under management, rightclick and select Database Mail Configuration Wizard. Choose Manage Database Mail accounts and profiles, click next Choose Create a new account, click next Enter account name, SMTP server and credentials. Click finish.

To use transactSQL use below code: EXECUTE msdb.dbo.sysmail_add_account_sp @account_name = 'database Administrator', @description = 'dba smtp account', @email_address = 'dba@tinydomain.com', @mailserver_name = 'smtp.tinydomain.com' ;

How to create a Database Mail profile Ensure that you have a list of database mail accounts you want to use within the database mail profile.

Open SQL Management Studio. Under management, rightclick, and select Database Mail Configuration Wizard. Choose Manage Database Mail accounts and profiles, click next Choose Create a new profile, click next Follow on screen instructions.

SQL Server 2012 Maintenance Plans

Maintenance plans in SQL Server 2012 is a wizard driven feature that allows DBAs to configure prebuilt administrative tasks such as backups, checking databases and database optimization.

These tasks are run by specified schedule by SQL Server agent. You can create workflow jobs using prebuilt tasks or custom script including powershell. Once plans are created, it allows you to edit add and remove steps within work flows. Maintenance plan allows DBAs to rearrange data on index and data pages by using a new fill factor by rebuilding indexes. Remove empty pages and compressing data can be scheduled using SQL maintenance plans. Performance gains can come from updating index statistics to ensure information is current. Data damage by be avoided by performing consistency checks routinely.

Backing up Database using SQL Maintenance Plans As a database administrator, its your responsibility to backup the databases to prevent database corruptions and bare metal failures. Using sql maintenance plans, you can perform full, diff and log backups. To create a backup job on SQL Server 2012 using maintenance plans: 1. In SQL Management Studio, go to Management 2. Rightclick maintenance plans and choose maintenance plan wizard. 3. Choose back up database, follow on screen instructions.

Note that you can do a lot more with maintenance plans than just backing up the databases. Database integrity check allows internal consistency check of the database then index database pages. Shrink Database allows dbas to shrink databases which compact the db and saves diskspace. This is done by clearing logs and empty data pages. Reorganize index function defrag indexes on sql tables and view which improves search performance. You may rebuild the whole index by running the rebuild index maintenance task which increases search times. The update statistics task make sure that table values are up to date and enable optimizer to make better decisions regarding data access. Note that you can also run SQL agent jobs within the maintenance plan allowing powershell scripts to be run.

Working with Resource Governor in SQL Server 2012

Resource governor allows system administrators and database administrators to limit the amount of resources the SQL Server database engine can consume. Note that this cannot be used with other SQL services such as reporting services. Incoming client requests can be controlled by specifying type of resource such as memory and processor. Workload is determined by query size and requests. The rule for workload can be changed dynamically without affording down time. When SQL Server 2012 is installed, internal resource pool and default resource pool is automatically created. You may create additional resource pools as needed. Internal workload groups and default workload groups are also created during install while allowing additional ones to be added. How Resource Governor works is that when SQL server receive a request, the session is classified, then routed to a workload group and it uses the resource pool assigned to the workload group.

How to turn on or off the Resource Governor 1. Open SQL Management Studio > Management > Resource Governor 2. You can rightclick Resource Governor and choose Enable or Disable.

Creating a resource pool for Resource Governor 1. 2. 3. 4. Open SQL Management Studio > Management > Resource Governor Rightclick Resource Governor and choose New Resource Pool Click the Name column and enter the name of the resource pool Now you should see the newly create resource pool under Resource Governor

How to create a new workload group 1. Open SQL Management Studio > Management > Resource Governor 2. Rightclick Resource Governor and choose properties. 3. In resources pool pane, click first column of newly created resource pool earlier. Enter the name you want to use for workload and click on to exit.

How to Rebuild SQL Server 2012 Master Database

Master DB All the system configuration settings and information is saved in the master DB. SQL instance specific settings such as linked servers, system config, endpoints and logon accounts. Note that SQL Instance will not start if master DB is missing. There are limitations to what you can do with the master DB. It makes very much sense that you cannot change the collation. Adding filegroups or files is not allow and you may not drop this database. This includes taking this DB offline. MSDB DB SQL Agent jobs and scheduling information is saved in msdb DB. Model DB contains a base setting for new DBs created on that SQL instance. This allows database administrators set a template for newly created databases. When you create database mail accounts and database mail profiles, it will be saved in msdb DB. Backup jobs and restore jobs history is handled by msdb DB. This includes data, time, devices, etc. In some cases you may need to rebuild these databases mentioned above. If you encounter data corruption in these databases, you must rebuild them. When you perform a rebuild, these databases are simply dropped and new default DB is created, just like a brand new SQL Instance install. It is implied that all data saved in these databases will be lost and restored to back to default configuration. To backup system settings prior to rebuilding the master db, run: 1. SELECT * FROM sys.configurations; 2. Copy and paste information to notepad. Now, to rebuild the databases, rerun setup with REBUILDDATABASE option. To do this, browse to installation CD and run: 3. Setup /QUIET /ACTION=REBUILDDATABASE /INSTANCENAME=SQLInstance [ /SQLCOLLATION=CollationName]

Managing SQL Server 2012 Databases

SQL Server 2012 database or a database is a set of structured data that contains tables and columns. Every column has a data type associated to it, rather be integer, double, currency or string. Multiple databases can reside in a single SQL server 2012 instance. Instance in SQL Server is an isolated installation that allows system administrators and database administrators to set various settings. SQL Server creates an EDB file for every database created. This is how SQL Server store the data on the server. To improve query performance, often these files are located on fast SAS 10K RPM disks or SAN hardware such as Netapp filers. Solid State Drives, SSDs are getting cheaper and this may be the future for IO intensive SQL databases. SQL Management Studio in SQL Server 2012 is a main tool used for managing SQL Server 2012 databases. This tool also includes a tool to run TransactSQL queries. Out of the box, every SQL instance contains five system databasesMaster DB, msdb DB, model DB, Resource DB, tempdb DB. Every database stores the data on filesystem using .edb and .ldf file. .EDB file stores all the data such as indexes, stored procedures and tables. Where .ldf file stores all database transactions that is required to recover the data. Filegroups in SQL Server consist of all data files that makes up the database. For example, you may have a primary data file that resides one drive and secondary data file that resides on the second drive.

Transporting a Database Between Servers You may need to copy or move a database between different SQL Servers. A lot of times for testing or dev environments, you need a copy of the current production database. There are a few options to get the job done:

You can use the database copy wizard If you can afford to take the database offline, you can deattached and reattach the database. To deattach a database, rightclick on the database, choose Tasks, then click on deattach.

How to Create a SQL 2012 Database To create a new database using SQL Management studio: 1. Open SQL Management Studio. 2. Rightclick Databases and choose New Database 3. You may also rename the newly created database by rightclicking and choosing rename.

To Increase the Database Size 1. Open SQL Management Studio. 2. Rightclick Databases and choose properties 3. Select files and enter value in Initial Size field.

How to Shrink the Database 1. Open SQL Management Studio. 2. Rightclick Databases, choose Tasks and click Shrink 3. Choose reorganize files before releasing unused space.

Managing SQL Server 2012 Databases

SQL Server 2012 database or a database is a set of structured data that contains tables and columns. Every column has a data type associated to it, rather be integer, double, currency or string. Multiple databases can reside in a single SQL server 2012 instance. Instance in SQL Server is an isolated installation that allows system administrators and database administrators to set various settings. SQL Server creates an EDB file for every database created. This is how SQL Server store the data on the server. To improve query performance, often these files are located

on fast SAS 10K RPM disks or SAN hardware such as Netapp filers. Solid State Drives, SSDs are getting cheaper and this may be the future for IO intensive SQL databases. SQL Management Studio in SQL Server 2012 is a main tool used for managing SQL Server 2012 databases. This tool also includes a tool to run TransactSQL queries. Out of the box, every SQL instance contains five system databasesMaster DB, msdb DB, model DB, Resource DB, tempdb DB. Every database stores the data on filesystem using .edb and .ldf file. .EDB file stores all the data such as indexes, stored procedures and tables. Where .ldf file stores all database transactions that is required to recover the data. Filegroups in SQL Server consist of all data files that makes up the database. For example, you may have a primary data file that resides one drive and secondary data file that resides on the second drive.

Transporting a Database Between Servers You may need to copy or move a database between different SQL Servers. A lot of times for testing or dev environments, you need a copy of the current production database. There are a few options to get the job done:

You can use the database copy wizard If you can afford to take the database offline, you can deattached and reattach the database. To deattach a database, rightclick on the database, choose Tasks, then click on deattach.

How to Create a SQL 2012 Database To create a new database using SQL Management studio: 1. Open SQL Management Studio. 2. Rightclick Databases and choose New Database 3. You may also rename the newly created database by rightclicking and choosing rename.

To Increase the Database Size 1. Open SQL Management Studio. 2. Rightclick Databases and choose properties 3. Select files and enter value in Initial Size field.

How to Shrink the Database

1. Open SQL Management Studio. 2. Rightclick Databases, choose Tasks and click Shrink 3. Choose reorganize files before releasing unused space.

Disadvantages of Contained Databases All these great features do come with some disadvantages. Majority are related to USER WITH PASSWORD authentication process. Database administrators can accidently give users access

to the database by attaching a contained database. To prevent this, you must bring up the database in RESTRICTED_USER mode. Kerberos authentication cannot be used with contained databases.

Moving to contained database After you understand the risk of moving to a contained database, follow below instructions to move to a contained database. To convert a database to a contained database using SQL Management Studio, follow: 1. Open SQL Management Studio 2. Rightclick your SQL Server and choose properties. 3. Got o Advanced page, configure enable contained database to True, under Containment section. 4. Now, rightclick on the database you wish to convert, choose properties 5. Go to Options page, configure Containment type to Full (or partial, if you wish), click OK.

You may also perform the same task using TransactSQL. Run the below commands to convert to contained database. sp_configure 'show advanced options', 1 ; GO RECONFIGURE ; GO sp_configure 'contained database authentication', 1; GO RECONFIGURE ; GO sp_configure 'show advanced options', 0 ; GO RECONFIGURE ; GO USE [master] GO ALTER DATABASE [ApplicationDB] SET CONTAINMENT = PARTIAL GO

SQL Server 2012 Database Snapshots Feature

This feature in SQL Server 2012 allows creation of a production database in read only form. Snapshots in SQL Server 2012 works at the data layer and simply data is copied from source to destination snapshot. Snapshot can be created for a database on the same server as the source database. Multiple snapshots can be created against a single database. Note that these are database snapshots, which is different from VSS snapshots which are used during the backup process. As mentioned earlier, this ready only copy of the database can be used to query reports while not affecting production server performance. If you need to back test the database and need to go back to point in time for reports, snapshots can be used. A lot of organizations makes a snapshot every financial quarter and save the snapshot for reporting purposes. Database snapshots are highly recommended when performing maintainence on the server. This allows database administrators to go back in time if corruption occurs. Administrator errors such as dropped table can be easily fixed if you had database snapshots. Here are a few requirements and gotchas for Database snapshot feature in SQL 2012:

Source database cannot be offline You may create a snapshot from secondary copy of alwayson Availability group. Scalable shared database not be configured on source database. The source database cannot be detached or dropped while snapshot exist. Source database and snapshot copy must be on same SQL Server Instance. Snapshots are not compatible with system databases You may not backup or detach a snapshot.

Creating a snapshot SQL Server management studio does not support snapshots function. This means only way to create snapshots is good old TransactSQL. To create a database snapshot in SQL Server 2012, run below: CREATE DATABASE name_of_the_snapshot ON ( NAME = filename, FILENAME = 'file_name' ) [ ,...n ] AS SNAPSHOT OF orginalDBname [;]

Restoring a snapshot If your primary database, aka source database becomes corrupt, you may need to restore it from the snapshot created earlier. Note that all changes after the snapshot will be lost. If there is a data

corruption, ensure that corruption occurred after the snapshot. In this case, primary database will be overwritten with the snapshot. To restore a snapshot run below command: RESTORE DATABASE db_name FROM DATABASE_SNAPSHOT = db_snapshot_name

Deleting a snapshot Its ideal to delete a snapshot if no longer needed. This will free up resources and disk from the server. To delete a snapshot database, run below command: DROP DATABASE snapshot_db_name

SQL Server 2012 Full-Text Search Configuration

Fulltext search feature in SQL Server 2012 is enabled by default. You must setup full text indexing on columns, if you need to use fulltext index on a table. FullText Search Database configuration DBA must perform basic steps to setup table columns within database for full-text search: 1. DBA must create a fulltext catalog. 2. You can create fulltext index by selecting each columns specifically you want to include in the fulltext. 3. You must specify a table column if given column contains docs stored as binary data including images. 4. You must dictate the language you want fulltext search to use. Full text search allows multiple languages though the use of word breakers and stemmers, stop list.

FullText Catalog and Index Setup 1. All fulltext index must fit to a full-text catalog. You may create a separate catalog for each index or you can associate one than one indexes with a catalog. Basically, fultext catalog is a virtual object and logical in nature. 2. Create a full-text index on the table or indexed view.

3. A full-text index is a distinct type of token-based practical index that is built and maintained by the Full-Text Engine. To generate full-text search on a table or view, it must have an exclusive, single-column, non-nullable index. The Full-Text Engine requires this unique index to map each row in the table to a unique, compressible key. A full-text index can include char, varchar, nchar, nvarchar, text, ntext, image, xml, varbinary, and varbinary(max) column.

FullText Indexes VS regular default SQL Server indexes


Full-text indexes Only one full-text index allowed per table. Regular SQL Server indexes Several regular indexes allowed per table. Updated automatically when the data upon which they are based is inserted, updated, or deleted. Not grouped.

The addition of data to full-text indexes, called a population, can be requested through either a schedule or a specific request, or can occur automatically with the addition of new data. Grouped within the same database into one or more full-text catalogs.

FullText Index Options Choosing the Column Language For information about things to consider when you are choosing the column language, see Choose a Language When Creating a Full-Text Index. Choosing a Filegroup for a Full-Text Index The procedure of building a full-text index is fairly I/O exhaustive (on a high level, it consists of reading data from SQL Server 2012, and then spreading the filtered data to the full-text index). As a best exercise, locate a full-text index in the database filegroup that is best for maximizing I/O performance or locate the full-text indexes in a different filegroup on another volume. When ease of organization is important to you, we endorse that you store table data and any associated full-text catalogs in the same filegroup. Occasionally, for performance reasons, you may want to have the table data and the full-text index in diverse filegroups that are stored on different volumes to make best use of I/O parallelism. Assigning the Full-Text Index to a FullText Catalog. It is significant to plan the assignment of full-text indexes for tables in full-text catalogs.

We endorse associating tables with the same update features (such as small number of variations versus large number of changes, or tables that alter often during a particular time of day) together under the same full-text catalog. By setting up full-text catalog population schedules, full-text indexes stay synchronous with the tables without unfavorably affecting the resource usage of the database server during periods of high database activity. When you allocate a table to a full-text catalog, contemplate the following guidelines: Always choose the smallest single index available for your full-text unique key. (A 4-byte, integer-based index is best.) This decreases the resources required by MS Search service in the file system suggestively. If the main key is large (over 100 bytes), consider selecting another unique index in the table (or creating another unique index) as the full-text sole key. Otherwise, if the full-text unique key size exceeds the maximum size allowed (900 bytes), full-text population will not be able to proceed.

Creating Views and Virtual Tables in SQL Server 2012

A view in SQL Server 2012 is a way to dynamically viewing data my query. You can look at a virtual table, where it pulls data from various tables and display the data in one view. Very similar concept as libraries in Windows 7 and dynamic distribution list Exchange. SQL Server 2012 does this by getting data from column and rows across multiple tables and placing them in a single view. Note that it also allows tables across different databases. SQL views can be used in RBAC, role based access control model, where you only want to grant a set of tables for a group of end users. There are various types of views within SQL Server 2012 and I will go over each of them. Systems view in SQL 2012 allows views of metadata in the catalog. This allows database administrators to view configuration on specific views such as list of user databases in the instance. Partition views in SQL 2012 are views that connect parallel partitioned data from a group of tables stripped across multiple servers. This allows you to present a single virtual table of the data from different SQL Servers. How to create a view in SQL 2012 1. Open SQL Server Management Studio. 2. On the left pane, rightclick Views, click on Add New View 3. On here, select a desired query. You may also create transactSQL to create the view be running command below.

CREATE VIEW allmarketing_view AS SELECT marketing FROM hrtable.Employee You may also change the view by running below command. ALTER VIEW allmarketing_view AS SELECT IT FROM hrtable.Employee

What are Stored Procedures in SQL Server 2012

Stored procedures are list of commands that performs a certain tasks. This allows database administrators to run set of TransactSQL commands. Just like scripts, they can be written to accept parameters and arguments. You may input and return data just like scripts. Since stored

procedures are run as a whole, this save network bandwidth instead of running single commands. Stored procedures are perfect when you have to perform set of tasks more than once. This allows you to reuse the same set of stored procedures instead of running set of commands manually. This allow decreases mistakes and keeps the environment consistent. There is various types of stored procedures, System, temporary and User-definded procedures. System stored procedures are built-in to SQL 2012 and located in hidden resource database. User defined databases can be user defined stored procedures. Creating a Stored Procedure (using SQL Management Studio) 1. 2. 3. 4. 5. Open SQL Management Studio under SQL Server 2012 Under Databases, expand the database, then Programmability Rightclick stored procedures and click New stored procedure. Enter Author, Create Date, Description, Procedure name Follow on screen instructions.

To create a stored procedure using TransactSQL use below code: USE EMPLOYEEDATABASE; GO CREATE PROCEDURE HR.uspGetEmployeesTest2 @LastName nvarchar(50), @FirstName nvarchar(50) AS SET NOCOUNT ON; SELECT FirstName, LastName, Department FROM HR.vEmployeeDepartmentHistory WHERE FirstName = @FirstName AND LastName = @LastName AND EndDate IS NULL; GO

SQL Server 2012 System Databases


SQL Server uses system DBs to support different parts of the DB management system (DBMS). Each DB plays a specific role and stores info that SQL Server needs to do its job. The system DBs are much like the user DBs generated in SQL Server. They store data in tables and contain the views, stored procedures, and other DB objects that you also see in user DBs. They also have associated DB files (that is, .mdf and .ldf files) that are physically located on the SQL Server machine.

The folder where each of these DB files is located depends on the SQL Server installation. By default, the installation process places these files in a folder named c:\Program Files\MS SQL Server\MSSQL. 1 \MSSQL\Data\.

Mater DB The master DB contains server-wide info about the SQL Server system. This server-wide info includes logins, linked server info, config info for the server, and info about user DBs generated in the SQL Server. The actual locations of the DB files and key properties that relate to each user DB are stored in the master DB. SQL Server cant start without a master DB. This is not surprising, given the type of info that it contains. Without the master DB, SQL Server does not know the location of the DBs that it services and does not know how the server is configured to run.

Resource DB The resource DB contains all the system objects deployed with SQL Server 2012. These system objects comprise the system stored procedures and system views that logically appear in each DB but are physically stored in the resource DB. MS moved all the system objects to the resource DB to simplify the upgrade process. When a new release of the software is made available, upgrading the system objects is accomplished by simply copying the single resource DB file to the local server. Similarly, rolling back an upgrade only requires overwriting the current version of the resource DB with the older version. You do not see the resource DB in the list of system DBs shown in SQL Server Management Studio (SSMS). You also cant add user objects to the resource DB. For the most part, you should not be aware of the existence of the resource DB. It has DB files named mssqlsystemresources.mdf and mssqlsystemresources.ldf that are located in the Binn folder, but you cant access the DB directly. In addition, you do not see the DB listed when selecting DBs using system views or with system procedures, such as sp_helpdb. Model DB The model DB is a template on which all user-generated DBs are based. All DBs need to contain a base set of objects known as the DB catalog. When a new DB is generated, the model is copied to create the requisite objects. Conveniently, objects can be added to the model DB. As an example, if you want a certain table generated in all your DBs, you can create the table in the model DB, and it is then propagated to all subsequently generated DBs. Msdb DB The msdb DB is used to store info for the SQL Server Agent, the Service Broker, DB Mail, log shipping, and more. When you create and schedule a SQL Server Agent job, the job's parameters and execution history are stored in msdb. Backups and maintenance plan info are stored in msdb as well. If log shipping is imple-mented, critical info about the servers and tables involved in this process is stored in msdb. Distribution DB The distribution DB, utilized during replication, stores metadata and history info for all types of replication. It is also used to store transactions when transactional replication is utilized. By default, replication is not set up, and you do not see the distribution DB listed in SSMS. However, the actual data files for the distribution DB are installed by default.

Tempdb DB The tempdb DB stores temporary data and data objects. The temporary data objects comprise temporary tables, temporary stored procedures, and any other objects you can want to create temporarily. The longevity of data objects in the temporary DB depends on the type of object generated. Ultimately, all temporary DB objects are removed when the SQL Server service is restarted. The tempdb DB is re-generated, and all objects and data added since the last restart of SQL Server are lost. tempdb can also be used for some of SQL Server's internal operations. Large sort operations are performed in tempdb before the result set is returned to the client. Certain index operations can be performed in tempdb to offload some of the space requirements or to spread I/O. SQL Server also uses tempdb to store row versions that are produced from DB modifications in DBs that use row versioning or snapshot isolation transactions.

SQL Server 2012 Management Studio


If you have been working with SQL Server for a long time, you can remember the SQL Enterprise Manager that came with SQL Server 6.5. with SSMS, MS has moved back to the paradigm that existed then. Like the SQL Server 6.5 Enterprise Manager, SSMS offers an integrated environment where developers and DBAs alike can execute the DB tasks they need. Say goodbye to Query Analyzer, Analysis Manager, and a number of other separate tools used in SQL Server 2000 and say hello to SSMS, which offers "one-stop shopping" for most of your DB needs. The environment and windows displayed are completely customizable, with the exception of the document window area. The Object Explorer Details page is the default, but other pages, such as a query editor window, can take the focus in this tab-oriented section of the SSMS display. The dialogs that form the rest of the SSMS display are referred to as modules and comprise the Registered Servers and Object Explorer windows, as well as a number of other modules that can be displayed via the View menu found at the top of the SSMS display. You can configure each of the component windows in a number of ways; as an example, you can have them float, or you can hide, dock, autohide, or display them as tabbed documents in the document window area. The config that you choose for your SSMS display depends on the type of work you do with SQL Server as well as the type of person you are. The Auto Hide feature causes the component window to shrink to a tab along the left or right side of the display. When you mouse throughout the tab, the window automatically expands and stays expanded as long as the mouse cursor remains in the component window area. Auto Hide helps maximize the working real estate available in the document window for query development and the like. Docking many windows can clutter the screen, but this feature allows you to view many different types of info all at once. This is a matter of personal preference, and SSMS has made it very easy to change. The SSMS window environment comprise nonmodal windows that are sizable. The nonmodal windows allows you to execute multiple tasks at one time without needing to open another instance of the SSMS app. In SQL Server 2000, the Enterprise Manager users were forced to open another instance of the app during many administrative tasks to be able to continue with other work. With SSMS, you can open a backup with the Back Up DB dialog and then continue working with the Object Explorer or other modules in SSMS while the backup is running. This

ability is a great timesaver and helps improve overall productivity. Your ability to size the dialog boxes is another user-friendly feature that can seem minor but is quite handy on certain windows. As an example, the SQL Server 2000 Enterprise Manager Restore dialog had a fixed size. Viewing the backup set info in this relatively small (nonsizable) dialog box was a challenge. The Restore dialog in SQL Server 2012's SSMS can contain a slew of info related to the backup sets available for restore. The ability to size the windows allows for much more info to be displayed. The tabbed document window area offers some usability improvements as well. This area, as described earlier, is fixed and is always displayed in SSMS. Component windows can be displayed in this area, along with windows for the Query Editor, diagrams, and other design windows. If desired, you can change the environment from a tabbed display to multipledocument interface (MDI) mode. In this mode, each document is opened in its own window within the document window. The MDI mode manages windows like the SQL Server 2000 Query Analyzer and can be more user-friendly for some people. You can change to MDI mode by selecting Tools, Options and then selecting MDI Environment from the General page. One particularly useful window that can be displayed in the document window is the Object Explorer Details page. This new window displays info relative to the node selected in the Object Explorer and includes options to produce in depth reports and graphs. The Object Explorer Details page is displayed in the document window by default when SSMS is launched, but you can also display it by pressing F7 or choosing Object Explorer Details from the View menu. The Object Explorer Details page has been vastly improved in SQL Server 2012. If you're familiar with the previous version, there is much more info displayed in SQL Server 2012 than there was in 2008. The nice part is that you can customize the info that is displayed and save those changes so that they are used the then time you open SSMS. As an example, when you RightClick on a column heading (such as Name), you see all the columns available for display. Only handfuls are displayed by default, but more than 30 available columns relate to DBs. The columns that are available depend on the type of object selected in the Object Explorer window. Another significant change in the Object Explorer Details page is the Object Search box. The Object Search box, located at the top of the Object Explorer Details page (then to the Search label), allows you to search for objects by name. You can use wildcards (as an example, Product%), or you can type a specific name you are looking for. The results are displayed in the Object Explorer Details page. Keep in mind that the objects that are searched depend on what is selected in the Object Explorer window. As an example, if you highlight the DBs node, you search all the DBs on your SQL Server. If you choose a specific DB, only that DB is searched.

SQL Server 2012 Security Model


The SQL Server 2012 security ideal is the best place to start to comprehend SQL Server security. The model is founded on three classes that separate the basic foundations of security: PrincipalsPrincipals are the objects that demand security to SQL Server resources. They include Windows users, SQL Server users, and database users. ObjectsObjects are the SQL Server resources to which permissions can be granted. PermissionsPermissions link principals with objects. Below shows the security mechanisms contained in each tier of the SQL Server 2012 security model. The columns are ordered from left to right, originated on the way security is recognized. Principals Windows: Groups Domain Login Local Login SQL Server: SQL Login Server Role Permissions GRANT/REVOKE/DENY CREATE ALTER DROP CONTROL CONNECT SELECT Securables Server Scope Login Endpoint Database Database Scope User Role

Some complication has been introduced, based on the classified nature of some of the security modules. Security can be recognized on these classified components, which in turn flows the security to the fundamental components. In addition, not all the permission mechanisms apply to every object. Many of the objects have a select number of authorizations that apply to them; equally, many permissions apply only to a select number of objects. As an example, SELECT permission is applicable to objects such as tables and views but would not be suitable for stored procedures. Authentication Modes The first level of security come across when accessing SQL Server is known as authentication. The authentication procedure performs the authentication needed to allow a user or client machine to connect to SQL Server. This linking can be granted via a Windows login or SQL Server login. Windows Authentication Mode Windows Authentication mode authorizes the account name and password, using info stored in the Windows OS. A Windows account or group must be recognized first, and then security can be established for that account in SQL Server. This manner has the benefit of providing a single login account and the ability to leverage domain security features, such as password length and expiration, account locking, encryption, and auditing. MS endorses this method.

Mixed Authentication Mode Mixed authentication permits for both Windows authentication and SQL Server authentication. SQL Server authentication is founded on a login that is produced in SQL Server and lives in SQL Server only. No Windows account is convoluted with SQL Server authentication. The account and password are established and preserved in SQL Server. SQL Server logins can be created with stronger password implementation that help better guard the login. SQL Server authentication is useful in situations in which a Windows DC does not control network access. It can also be useful for Web apps or legacy apps, where it may be burdensome to start a Windows user account for every connection to the database server.

How to Set SQL Server 2012 Authentication Mode You can choice the authentication mode when you install SQL Server, and you can alter it after the installation. To change the authentication mode afterward installation, you rightclick the server node in the Object Explorer and select the Properties option. When the Server Properties dialog performs, you select the Security page. The Security page permits you to specify

Windows Authentication mode or SQL Server and Windows Authentication mode (that is, mixed authentication). Any changes to the authentication mode need a restart of SQL Server to make the change effective.

Transparent Encryption in SQL Server 2012


TDE is a new feature introduced in SQL Server 2012 that allows an entire DB to be encrypted. Unlike column-level encryption, in TDE the encryption and decryption of data is performed automatically by the DB Engine, and this is fully transparent to the end user and apps. No changes to the DB or apps are needed. Consequently, TDE is the simpler choice when bulk encryption of data is necessary to meet regulatory compliance or corpo-rate data security standards. The encryption of a DB using TDE helps prevent the unauthorized access of data in the scenario in which physical media or backups have been lost or stolen. Transparent data encryption uses a DB encryption key (DEK) for encrypting the DB. The DEK is stored in the DB boot record and is secured by a certificate stored in the master DB. The DB master key is protected by the service master key, which is in turn protected by the Data Protection API. When TDE is enabled on a DB, attaching data files to another SQL Server or the restoring of a backup to another SQL Server is not permitted until the certificate that was used to secure the DEK is available. As an example, if a hard drive that contains DB files is stolen, without TDE, those DB files can be attached in another SQL Server, thus allowing access to the nonencrypted data in those files. With TDE, the data and log files are automatically encrypted, and the data within these files cant be accessed without an encryption key. Additionally, backups of DBs that have TDE enabled are also encrypted automatically. We're all familiar with stories about how backup tapes containing sensitive info have been lost or stolen. With TDE, the data in the backup files is completely useless without also having access to the key used to encrypt that data. The encryption and decryption of data with TDE are performed at the page level as data moves between the buffer pool and disk. Data residing in the buffer pools is not encrypted. TDE's specific purpose is to protect data at rest by encrypting the physical files of the DB, rather than the data itself. These physical files comprise the DB file (.mdf), transaction log file (.ldf), and backup files (.bak). Data pages are encrypted as they are written from the buffer pool to the DB files on disk. Conversely, the data is decrypted at the page level when the data is read in from the files on disk into the buffer pool. The encryption and decryption are done using a background process transparent to the DB user. Although additional CPU resources are necessary to implement TDE, overall, this approach offers much better performance than column-level encryption. According to MS, the performance hit averages only about 3-5%. TDE supports several different encryption options, such as AES with 128-bit, 192-bit, or 256-bit keys or 3 Key Triple DES. You make your choice when implementing TDE. Deploying Transparent Data Encryption Like many encryption scenarios, TDE is dependent on an encryption key. The TDE DB encryption key is a symmetric key that secures the encrypted DB. The DEK is protected using a

certificate stored in the master DB of the SQL Server where the encrypted DB is installed. Implementing TDE for a specific DB is accomplished by subsequent these steps:

Create a master key. Create or obtain a certificate protected by the master key. Create a DB encryption key and protect it by the certificate. Configure the DB to use encryption.

Using Command Line to Manage SQL Logins


You can administrator logins by using T-SQL statements. This method is usually not as easy as using the user-friendly GUI displays that come with SSMS, but occasionally using T-SQL is better. For example, with installations and upgrades that comprise changes to logins, you can use T-SQL to script the modifications and produce a repeatable process. SQL Server 2012 includes system stored procedures and an ALTER LOGIN declaration that you can use to administrator logins. The similar system stored procedures available in previous versions are still accessible in SQL Server 2012, but they have been denounced and will not be accessible in a upcoming version. Below lists the accessible system stored procedures and the basic function and current state of each one. The state specifies whether the process has been denounced and whether an alternate exists in SQL Server 2012. Function Add a SQL Server login. Change the default database. Change the default language. Deny server access to a Windows login. Drop a SQL Server login. Add a Windows login. Change a login's password. Drop a Windows login. Status Deprecated; use CREATE LOGIN. Deprecated; use ALTER LOGIN. Deprecated; use ALTER LOGIN. Deprecated. Deprecated; use DROP LOGIN instead. Deprecated. Deprecated; use ALTER LOGIN instead. Deprecated; use DROP LOGIN instead.

Store Procedure sp_addlogin sp_defaultdb sp_defaultlanguage sp_denylogin sp_droplogin sp_grantlogin sp_password sp_revokelogin

The system stored procedures have a selection of parameters, which are recognized in Books Online. Because they have been denounced, they are not the emphasis of this section. Instead, this section emphases on a numeral of examples that utilize the

CREATE, ALTER, and DROP statements. The subsequent example makes a SQL Server login with a password that must be changed the first time the login connects: CREATE LOGIN Larry WITH PASSWORD=N1 mepassw0rd$1 MUST_CHANGE, CHECK_EXPIRATION=ON You may then use the following ALTER LOGIN statement to alter the default database, language, and password for the new Laura login: ALTER LOGIN [Laura] WITH DEFAULT_DATABASE=[AdventureWorks2008], DEFAULT_LANGUAGE=[British], PASSWORD=myStrOngPW Finally, you can drop the Laura login by using the following: DROP LOGIN [Laura] As you see, the T-SQL statements for Logins are moderately easy to use. To shorten matters, you can generate T-SQL statements from SSMS. To do so, you click the Script button available on the screen that performs after you specify a login action. if you rightclick a login and select Delete, the Delete Object screen appears. At the top of this screen is a Script button. When you click this button, SSMS scripts the related T-SQL statements into a queryeditor window for you to review-and-execute.

SQL Server 2012 Providers and Drivers Explained


A worker is software used for opening various data stores in a reliable manner conforming to a specification, such as OLE DB. A provider may contain an API. SQLClients that use providers are known as customers. SMSS and SQLCMD, for example, are consumers of the SNAC OLE DB provider. You can choose from the subsequent providers:

SQL Native Client OLE DB providerThis is the newest OLE DB provider, and it is constructed into SNAC; it is also known as SQLNCLI. COM apps might want to switch to this provider to access the newest functionality; this also offers access to SQL Server 7 and 2000 DBs. .NET Framework data provider for SQL ServerThis data provider is accumulated in to the System. Data .SqlClient namespace in the .NET Framework. Managed code apps should use it to access the newest SQL Server 2012 functionality from .NET 3.5 apps. .NET 1.0, 1.1, and 2.0 apps do not have access to all the newest SQL Server 2012 functionality over this provider. MS OLE DB provider for SQL ServerThis OLE DB provider, known as SQL0LEDB, is dedicated for accessing SQL Server data and is distributed with MDAC. COM apps may continue to use it to access SQL Server 2012, or they can change to SQLNCLI for the newest functionality. MS OLE DB provider for ODBCThis denounced OLE DB provider, known as MSDASQL, is dispersed with MDAC. ADO apps can carry on to use it to access SQL Server 2012, but SQL Server does not support the newest SNAC-specific OLE DB functionality. MS has also made available a few implementation specific OLE DB

providers, such as the OLE DB provider for DB2, a COM component for integrating IBM DB2 and SQL 2012 data. A driver in this context can be defined as software that obeys to a standard such as Open DB Connectivity (ODBC) and offers an API for retrieving a specific type of data store, osql.exe is a good example of an app that customs an ODBC driver (the SNAC driver). These are the available drivers:

SQL Native Client ODBC driverThis is the newest ODBC driver, and it is built into SNAC. COM apps might want to switch to this driver to access the newest functionality. MS ODBC driver for SQL ServerThis is the ODBC driver distributed with MDAC for accessing SQL Server DBs. COM apps can endure to use it to access SQL Server 2012, or they can change to the SNAC ODBC driver for the newest functionality. This driver also offers access to SQL Server 7, 2000, and 2005 DBs. Jav a DB Connectivity (JDBC) driverThe JDBC driver was built precisely for accessing SQL Server data from Java code.

SQL Server 2012 System Stored Procedures


System stored procedures have been a favorite of SQL Server DBAs since the inception of SQL Server. They provide a rich set of info that covers many different aspects of SQL Server. They can return some of the same types of info as system views, but they generally return a fixed set of info that cant be modified as you can when using a CHOOSE statement against the system views. That is not to say that they are not valuable; they are valuable, and they are particularly useful for people who have been using SQL Server for a long time. System stored procedures such as sp_who, sp_lock, and sp_help are tools for a DB professional that are as basic as a hammer is to a carpenter. System stored procedures have names that start with sp_, and they are found in the sys schema. They are global in scope, which allows you to execute them from any DB, without qualifying the stored procedure name. They also run in the context of the DB where you are working. In other words, if you execute sp_helpf ile in the AdventureWorks2012 DB, the DB files for the AdventureWorks2012 DB are returned. This same type of behavior exists for any stored procedure that is generated in the master DB with a name that starts with sp_. As an example, if you create a procedure named sp_helpme in the master DB and execute that procedure in the AdventureWorks2012 DB, SQL Server ultimately looks for and finds the procedure in the master DB. System stored procedures are listed in the Object Explorer, in the Programmability node within Stored Procedures and then System Stored Procedures. There are far too many system stored procedures to list or discuss them all here. A quick check of the master DB lists more than 1,000 procedures. SQL Server Books Online offers in depth help on these procedures, which it groups into 18 different categories. You are likely to use only a handful of system stored procedures on a regular basis. What procedures you use depends on the type of work you do with SQL Server and your capacity to remember their names. below contains a sample set of system stored procedures that you can find useful. Description

System

Stored Procedure sp_configure Displays or changes server-wide configuration settings. sp_createstats sp_help Creates statistics that are used by the Query Optimizer for all tables in a database. Provides details about the object that is passed to it. If a table name is passed to this procedure, it returns information on the columns, constraints, indexes, and more. If no parameters are supplied, returns relevant database information (including the space used) for all the databases on an instance of SQL Server. Lists the database files associated with the database you are connected to. Displays current locking information for the entire SQL Server instance. Provides the number of rows and disk space used by the table, indexed view, or queue passed to it. Lists current processes that are connected to an instance of SQL Server.

sp_helpdb sp_helpfile sp_lock sp_spaceused sp_who

Becoming familiar with some of the system stored procedures is well worth your while. Using them is a very fast and effective means for gathering info from SQL Server. They do not require the formation of a CHOOSE statement, and using them is often the easiest way to get info via a query window.

Auditing in SQL Server 2012


Introduced with SQL Server 2012 is the SQL Server Audit feature. This long-overdue feature now adds a great native auditing functionality into the SQL Server DB Engine. An audit is the combination of several elements into a single package for a specific group of server actions or DB actions. The modules of SQL Server Audit combine to produce an output that is called an audit. The SQL Server Audit feature in SQL Server 2012 is intended to replace SQL Trace as the preferred auditing solution. SQL Server Audit is meant to provide full auditing capabilities, and only auditing capabilities, unlike SQL Trace, which also serves for performance debugging. The SQL Server Audit feature is built on top of Extended Events, a new high-performance eventing infrastructure introduced in SQL Server 2012. SQL Server Audit leverages the performance benefits of Extended Events, which offers both asynchronous and synchronous write capabilities (by default, SQL Server Audit uses the asynchronous eventing model). SQL Server Audit is also tightly integrated with the Windows OSs and can push (write) its audits to the Windows App or Security Event Log. With SQL Server Auditing, you can set up auditing of just about any event or execution within SQL Server, and it can be as granular as you need

(right down to a table and operation level). This ability is vital because not only can you track all these events, but you can use this auditing ability to fulfill app and DB audit compliance and look for patterns of misuse, or even specific "hot " objects that contain the most sensitive data in your DB. a branch under each DB called Security contains several of the common securityrelated nodes that you've seen before (Users, Roles, Schemas, and so on) . But now, there is a DB Audit Specifications branch from which you can set up and view the DB audit specifications you have defined. You can have as many specifications as you want, and again, they can be at varying levels of granularity. Before you can set up a DB Audit Specification, however, you need to first set up a SQL Server Audit object. To do this, you need to use a couple of new entries in the Object Explorer under the Security folder at the SQL Server level: Audits and Server Audit Specifications. Essentially, three main objects describe audits in SQL Server 2012:

The Server Audit objectUsed to describe the target for audit data, plus some toplevel config settings. This destination can be a file, the Windows App log, or the Windows Security log. The Server Audit object contains no info about what is being auditedjust where the audit data is going. Multiple Server Audit objects can be defined with each object independent from one another (that is, they can each stipulate a different destination). The Server Audit Specification objectUsed to describe what to audit at a server instance-wide level. A server audit specification need to be associated with a Server Audit object to define where the audit data is written. There is a one-to-one relationship between the Server Audit Specification object and the Server Audit object. The DB Audit SpecificationUsed to describe what to audit at a specific DB level. Where the audit data is written is determined by the Server Audit object it is associated with. Each DB audit specification can be associated withonly one server audit. A server audit can be associated with audit specifications for multiple DBs, but only one DB audit specification per DB.

To create a new Server Audit object, RightClick on the Audits item in Object Explorer and choose New Audit > When you set up a Server Audit object, you stipulate where the audit info will be written to. you can see that we are creating a server audit named NEW_SQL_Server_Audit and are defining it to use the App log at the Windows OS level as the audit destination. You can also choose to write to the Windows Security log or to a text file. Events written to the App or Security Event log can be accessed with Event Viewer or with dedicated Event log management software, such as MS Systems Center Operations Manager. After you set up the Server Audit object, the then step is to go to the DB Audit Specifications folder, in the DB for which you can want to set up auditing. RightClick this folder and choose New DB Audit Specification to bring up the dialog. This is where you define your DB-level audits. In the Create DB Audit Specification dialog, you stipulate the name of the DB Audit object and the Server Audit object it will be running under. In this example, the DB Audit name is NEW_DB_Audit_Specif ication, and it will be running under the NEW_SQL_Server_Audit Audit object defined in 13.9. In this example, the DB audit is being set up to audit any CHOOSE

statements (reads) run against the Employee table (which, of course, contains company-sensitive employee data) by any user (public). At this point you have produced a Server Audit object and DB audit specification associated with the server audit. However, neither of these audits is enabled. You can enable them by RightClicking on each and selecting Enable. As soon as the Server Audit object is enabled, it begins auditing and writing audit records to the specified destination (in this example, the Windows App log). You can review the details by RightClicking on the Server Audit and selecting View Audit Logs or, if you are auditing to the Windows App or Security Event Log, by opening the Windows Event Viewer directly. One of the advantages of opening the Audit log from within SSMS is that it automatically filters the log to show only SQL Server Audit events. you can see that we've opened the Log File Viewer and selected to view the App log (where we directed our SQL Server Audit to go). A few CHOOSE statements were run against the Employee table and, sure enough, the audit info of the CHOOSE statements displays up in the App log. Within the Log File Viewer, you can filter your audit results or search them to look for patterns, specific violations, and so on. From the Log File Viewer, you also have the option of exporting the audit logs to a text file or to a comma-separated values (CSV) file. With a CSV file, you could import the audit logs into a DB for further analysis and correlation. It's up to your security and audit team to decide how these audits are to be used. In addition to DB-level auditing of actions at the DB level, you can also set up auditing of server-level events, such as management changes and logon and logoff operations. These are set up in the SSMS Object Explorer throughout the Server Audit Specifications item in the Security folder for the SQL Server.

FileGroup Backups in SQL Server 2012


Much of our discussion thus far has focused on backing up an entire DB, but it is possible to back up only particular files or a group of files in a filegroup. A SQL Server DB, by default , has only two files: the data file (with the file extension .mdf) and the log file (with the extension .ldf). You can add additional files and filegroups that contain these files to extend the DB beyond the original two files. Thes e additional files are often data files added to larger DBs that require additional space. With very large DBs, performing a ful l backup tha t contains all the DB files can take too much time. In such a case, the individual files or filegroups can be backed up separately, enabling you to spread out the backup. BACKUP DB [AdventureWorks2012] FILE = 1 AdventureWorks2012_ReadOnlyData' TO DISK = N'E:\mssql2012\backup\AdventureWorks2012_ReadOnlyData.bak1 WITH NOFORMAT, INIT, NAME = N1 AdventureWorks2012-Readonly File Backup1 , SKIP, NOREWIND, NOUNLOAD, STATS = 10 There is some additional administrative overhead associated with file and filegroup backups. Unlike a full DB backup that produces one file that contains the entire DB, the file backups do not stand by themselves and require other backups to be able to create the entire DB. You need to keep the subsequent points in mind when performing file and filegroup backups:

A file or filegroup backup does not back up any portion of the transaction log. To restore a file or filegroup backup, you need to have the transaction log backups since the last file or filegroup backup, including the tail of the log, for the DB system to confirm transactional reliability. This also implies that the DB need to be in full or bulk-logged recovery because these are the only models that support transaction log backups. Individual file or filegroup backups can be restored from a full DB backup. Point-in-time recovery is not permitted with file or filegroup backups. Differential backups can be combined with file or filegroup backups. These differential backups capture only those extents that have changed since the file or filegroup backup was made.

File and filegroup backups can be very powerful options for very large DBs, but you need to confirm that the relevant backups can be accounted for. In all backup situations, the key to a successful plan is testing your backup strategy; this is particularly true with file and filegroup backups.

Potrebbero piacerti anche