Friday, March 22, 2013

Fix: Error: 15138 – The database principal owns a schema in the database, and cannot be dropped

If you try to drop a user that owns a schema, you will receive the following error message:

The database principal owns a schema in the database, and cannot be dropped.

In order to drop the user, you need to find the schemas they are assigned, then transfer the ownership to another user or role.

SELECT s.name
FROM sys.schemas s
WHERE s.principal_id = USER_ID('<USER_Name>')


-- now use the names you find from the above query below in place of the SchemaName below

ALTER AUTHORIZATION ON SCHEMA::SchemaName TO dbo

Thursday, February 7, 2013

SQL SERVER DBA CONCEPTS

SQL SERVER DBA CONCEPTS

CORE DBA CONCEPTS of SQL SERVER 

The History of SQL Server and Relational Databases
Relational database history and SQL Server and ANSI Standards
Relation between Application and Database

Overview of Windows Concepts
Role of Windows Operating System in SQL Server Administration
Windows Operating System Basics
Overview of Built-in accounts, Service accounts
Overview of Users and Groups
Overview of Services

Overview of Network Concepts
Role of Network in SQL Server Administration
Basics of Network Concepts, Network drives
Introduction to Work Group, Domain
Introduction to Active Directory Services (ADS)
Introduction to Domain Controller (DC)
Introduction to Domain Naming Server (DNS)
Introduction to Dynamic Host Configuration Protocol (DHCP)

SQL Server Editions
Different Editions of SQL Server and their features
Tools, Utilities and Components of SQL Server
Choosing Appropriate SQL Server Edition
Licensing issues with SQL Server

Installing and Configuring SQL Server
Pre-installation steps and Installation SQL Server
Configuring the run-time SQL Server system
Patching SQL Server - Service Packs, Hot fixes
Finding Right Service Pack or Hot Fix to be installed
Problems and precautions involved in SQL Server Patching
Upgradation from SQL server 2000/2005 to 2008 and Migration



SQL Server Databases
System Databases Master, MSDB, Model, Temp and Resource
Creating User Databases

SQL Server Data Storage Management
SQL Server File Management Architecture
Creating Database Files
Creating SQL Server Log Files
Using SQL Server File groups
Moving Files or File Groups

SQL Server Security Management
Windows Security Management for the server
Windows Authentication Model
SQL Server Rights and Role Management
SQL Server Authentication and Mixed Mode Authentication
Logins
Mapping roles and databases to logins

SQL Server Backup & Recovery
Overview of SQL Server Backup and Recovery
Full Backups, Incremental Backups and Log Backups
Overview of Backupset, Backupmediaset, Backupmediafamily
Recovery Models in SQL Server
Restoring a SQL Server Database
Difference between Restore and Recovery
Performing Recovery
Backup and Restore through third party tools like Redgate

Overview of Testing, Development, Staging and Production Server Environments
Designing Production server from Test Server and Vice versa
Naming Convention for servers(Compliant to Industry Standards)

SQL Architecture and Memory
Physical Database Architecture
Relational (Logical) Database Architecture
Memory Management

Physical Database Engine Architecture
Pages and Extents
Physical Database Files and Filegroups
Space Allocation and Reuse
Table and Index Architecture

Relational Database Engine Architecture
Query Process Architecture
Memory Architecture
Managing Memory for Large Databases
Thread and Task Architecture
Understanding Non-Uniform Memory Access (NUMA)
Buffer Management
Distributed Query Architecture

Management
Policy Management
Configuring Database Mail
SQL Server Logs
Distribution Transaction Coordinator
Data Collection and Resource Governor (In 2008 only)

SQL Server Agent
Jobs and Job Activity Monitor
Alerts
Operators
Proxies
Error Logs

SQL Server Job Scheduling
Common Database Scheduled Jobs
Setting SQL Server and server alerts thresholds
Creating Customized Error Conditions
Scheduling multi-step job streams
Troubleshooting of failed Jobs

Maintenance Plans
Overview of Maintenance Plan
Tasks in Maintenance Plans
Creation of Maintenance Plan
Monitoring Maintenance Plan
Troubleshooting of failed Jobs created by Maintenance Plan

DBCC Commands
Introduction to Database Console Commands
Maintenance DBCC Commands
Informational DBCC Commands
Validation DBCC Commands
Miscellaneous DBCC Commands

Metadata
Understanding Metadata and its importance
System Tables and Dynamic Management Views(DMV), System Stored Procedures
Querying System Tables, DMV’s and Stored Procedures to obtain Metadata
Role of Master and MSDB in maintaining Metadata

SQL Server Configuration Manager (SSCM)
Managing Services with SQL Server
Starting and Stopping Instance from SSCM
Starting and Stopping SQL Agent from SSCM
Configuring Protocols, Ports and Aliases in SSCM
Introduction to SSIS and DTS
Using DTS to export and Import SQL Server Table data


HIGH AVAILABILITY
Overview of Disaster Recovery and High Availability solutions
Disaster types
Recovery solutions
Standby database overview
High Availability

SQL Server Database Replication
Replication Components and Replication Terminology
Replication Topologies – Central Publisher, Central Publisher with Remote Distributor, Central
Subscriber, Central Distributor, Publishing Subscriber
Types of Replication – Snapshot Replication, Merge Replication and Transactional Replication,
Peer-Peer Replication
Configuring Replication – Merge Replication , Transactional Replication, Snapshot Replication

Log Shipping
Log Shipping Overview
Log Shipping Deployment and Administration
Configuring Log Shipping using Management Studio and T-SQL
Monitoring Log Shipping

Database Mirroring
Important:
Introduction
Database Mirroring Overview
Database Mirroring Dynamics
Database Mirroring Availability Scenarios
Implementing Database Mirroring
Database Mirroring and High Availability Technologies
Conclusion

SQL Server Clustering
Overview of Clustering
Hardware and Software Requirement for Clustering.
Installing and Configuring VMWARE for building virtual environment
Installing Windows 2008 clustered environment
Installing SQL Server Active Passive (Cluster) on Windows 2008 clustered environment
Adding a node to existing SQL Server cluster
How to patch SQL Server Clustered Environment by applying SP1 on SQL Server 2008 cluster instance.
What is SQL Server Active Active Clustering
Installing SQL Server Active Active Clustering
Installing Analysis Services (SSAS) on a clustered environment
Installing / Configuring Integration Services (SSIS) on a clustered environment
Remove a node from a running clustered instance
Un-installing SQL Server Cluster

PERFORMANCE TUNING


SQL Architecture and Memory
Physical Database Architecture
Relational (Logical) Database Architecture
Memory Management

Table and Index Structure
Partitioning Tables
Partitioning Index
Clustered Index
Table Scan and Index Scan
Index Seek vs. Index Scan

Locking and Concurrency
Locking Mechanism
Types of Locks
Isolation Levels in SQL Server
Live Lock, Dead Lock and Blocking detection and resolution
Killing processes at OS level

Query Optimization and Programming Efficiency
T-SQL Tuning
Query execution Plan
Estimated Execution Plan

SQL Server performance counters
Understanding different Performance Counters
Processor:% Processor Time
PhysicalDisk:Avg.Disk Queue Length
PhysicalDisk: Disk Read Bytes/sec and Physical Disk: Disk Write Bytes/sec

Server Performance and Activity Monitoring
Perform monitoring tasks with Windows tools
Create SQL Server database alerts with Windows tools
Perform monitoring tasks with SQL Server Management Studio
Perform monitoring tasks with SQL Trace by using Transact-SQL stored procedures
Create and modify traces by using SQL Server Profiler
Start, pause, and stop traces by using SQL Server Profiler
Open traces and configure how traces are displayed by using SQL Server Profiler
Replay Traces by using SQL Server Profiler
Create, modify, and use trace templates by using SQL Server Profiler
Use SQL Server Profiler traces to collect and monitor server performance



Database Engine Tuning Advisor
Create Workloads
Tune a Database
View Tuning Output
Implement Tuning Recommendations
Create XML Input Files
Perform Exploratory Analysis
Review, Evaluate, and Clone Tuning Sessions

Performance Tools and Monitoring
SP_TRACE_SETFILTER (T-SQL) for tracking engine process events
System Monitor for tracking resource usage
Activity Monitor in SSMS to display Processes running on an instance, Blocked Processes,Locks,User activity
System Stored Procedures
DBCC(T-SQL)
Built-in-Functions(T-SQL)
Trace Flags(T-SQL)
SQL Server Profiler
Resource Governor
Data Collection

SQL Server performance tips
Proactive Actions that Ensure Optimized SQL Server Performance
Establishing a Smart SQL Server Monitoring Plan

Monday, January 7, 2013

SQL Server 2008 : Transparent Data Encryption

  • Transparent data encryption (TDE) is a new feature introduced in SQL Server 2008 that allows an entire database to be encrypted. 
  • Unlike column-level encryption, in TDE the encryption and decryption of data is performed automatically by the Database Engine, and this is fully transparent to the end user and applications.
  • The encryption of a database 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 database encryption key (DEK) for encrypting the database.
  • The DEK is stored in the database boot record and is secured by a certificate stored in the master database. 
  • The database 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 database, attaching data files to another SQL Server instance or the restoring of a backup to another SQL Server instance is not permitted until the certificate that was used to secure the DEK is available. 

Implementing Transparent Data Encryption:


Implementing TDE for a specific database is accomplished by following these steps:
  • Create a master key.
    USE master;
    GO

    --Create the master key which is stored in the master database
    CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'mystrongpassword$$';
    GO

  • Create or obtain a certificate protected by the master key.
    CREATE CERTIFICATE MyCertificate
    with SUBJECT = 'Certificate stored in Master Db'
    GO

  • Create a database encryption key and protect it by the certificate.
    USE AdventureWorks2008R2
    GO
    CREATE DATABASE ENCRYPTION KEY
    WITH ALGORITHM = AES_256
    ENCRYPTION BY SERVER CERTIFICATE MyCertificate
    GO

  • Configure the database to use encryption.
     ALTER DATABASE AdventureWorks2008R2
    SET ENCRYPTION ON
    GO 

    After you enable TDE, you might want to monitor the progress of the encryption. This can be done by running the following query:

    SELECT DBName = DB_NAME(database_id), encryption_state
    FROM sys.dm_database_encryption_keys ;
    GO
     


    DBName                           encryption_state
    --------------------                 ----------------------
    tempdb                                   3
    AdventureWorks2008R2        3

    This query returns the database encryption state. A database encryption state of 2 means that encryption has begun, and an encryption state of 3 indicates that encryption has completed. When the tempdb database and user database you are encrypting reach a state of 3, the entire user database and tempdb database are encrypted.
 
When TDE is enabled for a given database, encryption is applied to a variety of files related to the database, including the following:
  • Database Data Files— All data files that contain the database data are encrypted. These files typically have the extension .mdf or .ndf.
  • Database Log Files— The transaction log files are encrypted so that no clear text is visible in the files. These files typically have the extension .ldf.
  • Database Backups— All database backups, including full, differential, and log, are encrypted.
  • Tempdb— If any databases on a server are encrypted with TDE, the tempdb database is also encrypted.

Wednesday, November 28, 2012

SQL SERVER Interview Questions


  • What is RDBMS?
  • What are the Properties of the Relational Tables?
  • What is Normalization?
  • What is De-normalization?
  • How is ACID property related to Database?
  • What are the Different Normalization Forms?
  • What is a Stored Procedure?
  • What is a Trigger?
  • What are the Different Types of Triggers?
  • What is a View?
  • What is an Index?
  • What is a Linked Server?
  • What is a Cursor?
  • What is Collation?
  • What is the Difference between a Function and a Stored Procedure?
  • What is subquery? Explain the Properties of a Subquery?
  • What are Different Types of Join?
  • What are Primary Keys and Foreign Keys?
  • What is User-defined Functions? What are the types of User-defined Functions that can be created?
  • What is an Identity?
  • What is DataWarehousing?
  • What languages BI uses to achieve the goal?
  • What is Standby Servers? Explain Types of Standby Servers.
  • What is Dirty Read?
  • Why can’t I use Outer Join in an Indexed View?
  • What is the Correct Order of the Logical Query Processing Phases?
  • Which TCP/IP port does the SQL Server run on? How can it be Changed?
  • What are the Difference between Clustered and a Non-clustered Index?
  • What are the Different Index Configurations a Table can have?
  • What are Different Types of Collation Sensitivity?
  • What is OLTP (Online Transaction Processing)?
  • What’s the Difference between a Primary Key and a Unique Key?
  • What is Difference between DELETE  and TRUNCATE Commands?
  • What are Different Types of Locks?
  • What are Pessimistic Lock and Optimistic Lock?
  • When is the use of UPDATE_STATISTICS command?
  • What is the Difference between a HAVING clause and a WHERE clause?
  • What is Connection Pooling and why it is Used?
  • What are the Properties and Different Types of Sub-Queries?
  • What are the Authentication Modes in SQL Server? How can it be Changed?
  • Which Command using Query Analyzer will give you the Version of SQL Server and Operating System?
  • What is an SQL Server Agent?
  • Can a Stored Procedure call itself or a Recursive Stored Procedure? How many levels of SP nesting is possible?
  • What is Log Shipping?
  • Name 3 ways to get an Accurate Count of the Number of Records in a Table?
  • What does it mean to have QUOTED_IDENTIFIER ON? What are the Implications of having it OFF?
  • What is the Difference between a Local and a Global Temporary Table?
  • What is the STUFF Function and How Does it Differ from the REPLACE Function?
  • What is PRIMARY KEY?
  • What is UNIQUE KEY Constraint?
  • What is FOREIGN KEY?
  • What is CHECK Constraint?
  • What is NOT NULL Constraint?
  • What is the difference between UNION and UNION ALL?
  • What is B-Tree?
  • How to get @@ERROR and @@ROWCOUNT at the Same Time?
  • What is a Scheduled Job or What is a Scheduled Task?
  • What are the Advantages of Using Stored Procedures?
  • What is a Table Called, if it has neither Cluster nor Non-cluster Index? What is it Used for?
  • Can SQL Servers Linked to other Servers like Oracle?
  • What is BCP? When is it Used?
  • What Command do we Use to Rename a db, a Table and a Column?
  • What are sp_configure Commands and SET Commands?
  • How to Implement One-to-One, One-to-Many and Many-to-Many Relationships while Designing Tables?
  • What is Difference between Commit and Rollback when Used in Transactions?
  • What is an Execution Plan? When would you Use it? How would you View the Execution Plan?
  • What is Difference between Table Aliases and Column Aliases? Do they Affect Performance?
  • What is the difference between CHAR and VARCHAR Datatypes?
  • What is the Difference between VARCHAR and VARCHAR(MAX) Datatypes?
  • What is the Difference between VARCHAR and NVARCHAR datatypes?
  • Which are the Important Points to Note when Multilanguage Data is Stored in a Table?
  • How to Optimize Stored Procedure Optimization?
  • What is SQL Injection? How to Protect Against SQL Injection Attack?
  • How to Find Out the List Schema Name and Table Name for the Database?
  • What is CHECKPOINT Process in the SQL Server?
  • How does Using a Separate Hard Drive for Several Database Objects Improves Performance Right Away?
  • How to Find the List of Fixed Hard Drive and Free Space on Server?
  • Why can there be only one Clustered Index and not more than one?
  • What is Difference between Line Feed (\n) and Carriage Return (\r)?
  • Is It Possible to have Clustered Index on Separate Drive From Original Table Location?
  • What is a Hint?
  • How to Delete Duplicate Rows?
  • Why the Trigger Fires Multiple Times in Single Login?
  • What is Aggregate Functions?
  • What is Use of @@ SPID in SQL Server?
  • What is the Difference between Index Seek vs. Index Scan?
  • What is the Maximum Size per Database for SQL Server Express?
  • How do We Know if Any Query is Retrieving a Large Amount of Data or very little data?
  • What is the Difference between GRANT and WITH GRANT while Giving Permissions to the User?
  • How to Create Primary Key with Specific Name while Creating a Table?
  • What is T-SQL Script to Take Database Offline – Take Database Online
  • How to Enable/Disable Indexes?
  • Can we Insert Data if Clustered Index is Disabled?
  • How to Recompile Stored Procedure at Run Time?
  • Is there any Performance Difference between IF EXISTS (Select null from table) and IF EXISTS (Select 1 from table)?
  • What is Difference in Performance between INSERT TOP (N) INTO Table and Using Top with INSERT?
  • Does the Order of Columns in UPDATE statements Matter?
  • What are the basic functions for master, msdb, model, tempdb and resource databases?
  • What is the Maximum Number of Index per Table?
  • Explain Few of the New Features of SQL Server 2008 Management Studio
  • Explain IntelliSense for Query Editing
  • Explain MultiServer Query
  • Explain Query Editor Regions
  • Explain Object Explorer Enhancements
  • Explain Activity Monitors
  • What is Service Broker?
  • Where are SQL server Usernames and Passwords Stored in the SQL server?
  • What is Policy Management?
  • What is Database Mirroring?
  • What are Sparse Columns?
  • What does TOP Operator Do?
  • What is CTE?
  • What is MERGE Statement?
  • What is Filtered Index?
  • Which are the New Data Types Introduced in SQL SERVER 2008?
  • What are the Advantages of Using CTE?
  • How can we Rewrite Sub-Queries into Simple Select Statements or with Joins?
  • What is CLR?
  • What are Synonyms?
  • What is LINQ?
  • What are Isolation Levels?
  • What is Use of EXCEPT Clause?
  • What is XPath?
  • What is NOLOCK?
  • What is the Difference between Update Lock and Exclusive Lock?
  • How will you Handle Error in SQL SERVER 2008?
  • What is RAISEERROR? What is RAISEERROR?
  • How to Rebuild the Master Database?
  • What is the XML Datatype?
  • What is Data Compression?
  • What is Use of DBCC Commands?
  • How to Copy the Tables, Schema and Views from one SQL Server to Another?
  • How to Find Tables without Indexes?
  • How to Copy Data from One Table to Another Table?
  • What is Catalog Views?
  • What is PIVOT and UNPIVOT?
  • What is a Filestream?
  • What is SQLCMD?
  • What do you mean by TABLESAMPLE?
  • What is ROW_NUMBER()?
  • What are Ranking Functions?
  • What is Change Data Capture (CDC) in SQL Server 2008?
  • How can I Track the Changes or Identify the Latest Insert-Update-Delete from a Table?
  • What is the CPU Pressure?
  • How can I Get Data from a Database on Another Server?
  • What is the Bookmark Lookup and RID Lookup?
  • What is Difference between ROLLBACK IMMEDIATE and WITH NO_WAIT during ALTER DATABASE?
  • What is Difference between GETDATE and SYSDATETIME in SQL Server 2008?
  • How can I Check that whether Automatic Statistic Update is Enabled or not?
  • How to Find Index Size for Each Index on Table?
  • What is the Difference between Seek Predicate and Predicate?
  • What are Basics of Policy Management?
  • What are the Advantages of Policy Management?
  • What are Policy Management Terms?
  • What is the ‘FILLFACTOR’?
  • Where in MS SQL Server is ’100’ equal to ‘0’?
  • What are Points to Remember while Using the FILLFACTOR Argument?
  • What is a ROLLUP Clause?
  • What are Various Limitations of the Views?
  • What is a Covered index?
  • When I Delete any Data from a Table, does the SQL Server reduce the size of that table?
  • What are Wait Types?
  • How to Stop Log File Growing too Big?
  • If any Stored Procedure is Encrypted, then can we see its definition in Activity Monitor?

Wednesday, November 21, 2012

SQL SERVER – DBCC RESEED Table Identity Value – Reset Table Identity

DBCC CHECKIDENT can reseed (reset) the identity value of the table. For example, YourTable has 25 rows with 25 as last identity. If we want next record to have identity as 35 we need to run following T SQL script in Query Analyzer.

DBCC CHECKIDENT (yourtable, reseed, 34)

If table has to start with an identity of 1 with the next insert then table should be reseeded with the identity to 0. If identity seed is set below values that currently are in table, it will violate the uniqueness constraint as soon as the values start to duplicate and will generate error.

Restore failed for server - system.data.sqlclient.sqlError: exclusive access could not be obtained because database is in use


Error Readout:
Restore Failed for Server -- System.Data.SqlClient.SqlError:Exclusive access could not be obtained because the database is in use

Solution-1:
Run this SQL

USE master
GO
ALTER DATABASE <database name>
SET OFFLINE WITH ROLLBACK IMMEDIATE
ALTER DATABASE <database name>
SET ONLINE

Explanation:
Are you trying to restore a database. Slow down now buddy, there might be other people doing things to that database right now too. You could be polite, run a sp_who, see who's using your database and ask them if it would be ok to do a restore, but who are we kidding it's much more fun/quick to just kick them off. That's exactly what the above statement does.



Solution-2: 
Close all the applications which have a chance to access your database and try to restore. If you get same error after doing this then you can take your database offline by right click on the database. Go to Tasks and click on Make Offline. Once this done. Make it Online with the same manner and try to restore again. 

Solution-3:
Change the database access mode to single user.

USE 
MASTER 
GO      

ALTER DATABASE MyDatabase  
SET SINGLE_USER WITH ROLLBACK IMMEDIATE   
Go      

RESTORE DATABASE MyDatabase  
FROM DISK = N'[file address]'   
Go      
ALTER DATABASE MyDatabase  
SET MULTI_USER with ROLLBACK IMMEDIATE   
Go