Intro. Highly Availability

July 14th, 2009 Posted in High Availability, SQL Server  No Comments »

High availability of an application is a function of all components such as hardware, backup/recovery, operating system, vendor agreements, sufficient training, extensive quality assurance/testing, rigorous stands and procedures and some overall risk-mitigating strategies, such as spreading…

Backup, Training, Quality Assurance , Standard / Procedures, Server Instance isolation

1. Hardware

  1. Redundant power supplies ( and UPSs)
  2. Redundant fan systems
  3. Fault-tolerant disk, such as RAID ( 1 through 10 ), preferably “hot swappable”
  4. ECC memory
  5. Redundant Ethernet connections

2. Backup

3. Operating System

  1. Upgrades to your OS
  2. Antivirus software
  3. firewalls for external-facing systems

Vendor Agreements

  1. software licenses
  2. software support agreements
  3. hardware service agreements

Different Levels of HA:

  1. Microsoft Cluster Services ( non-SQL Server based )
  2. SQL clustering
  3. Data replication ( including peer-to-peer configurations )
  4. Log shipping
  5. Database Mirroring

Microsoft Cluster Services ( MSCS )

  1. MSCS is the advance windows operating system configuration that defines and manages between two and eight servers as “nodes” in a cluster.
  2. These nodes are aware of each other and can be setup to take over cluster-aware applications from any node that fails ( failed server ).
  3. This sluster configuration also share and controls one or more disk subsystems as part of its high-availability capability.
  4. MSCS is available only with MS Windows Enterprises Edition Advanced Server and Data Center OS.
  5. MSCS can be set up in an active/passive or active/active mode.If active or passive server fails other can take over share disk and cluster-aware applications in instaneously.

SQL Clustering ( Chapter 17 )

  1. Creating a SQL Server instance that is clustered is done by actually creting a virtual SQL server instance that is known to the application.
  2. two physical SQL server instances that share one set of databases.
  3. In an active/passive configuration, only one SQL server instance is active at a time
  4. If active server fails, the passive server simply takes over instantaneously.
  5. This is possible because MSCS also controls shared disk where the databases are.

Database does not have a valid owner

August 23rd, 2008 Posted in SQL Server, Security  No Comments »

Database diagram support objects cannot be installed because this database does not have a valid owner. To continue, first use the Files page of the Database Properties dialog box or the ALTER AUTHORIZATION statement to set the database owner to a valid login, then add the database diagram support objects

To fix the problem I first needed to attach the database to the management studio, this can be done in either the full product or the SQL Express Management Studio. Then by going to the properties for the database with the problem and selecting the files tab, change the owner to the [sa] account and select apply. Or you could use the following script.

USE [<DatabaseName>]
GO
EXEC dbo.sp_changedbowner @loginame = N'sa', @map = false
GO

SQL Server Security : Securables and Permissions

August 16th, 2008 Posted in SQL Server, Security  No Comments »

Securables - Securables are the SQL Server resources that permissions can be granted to.

Server Database Schema
Logins User Table
EndPoints Role View
Databases Application role Function
Assembly Procedure
Message Type Queue
Route Type
Service Synonym
Remote Service Binding Aggregate
Fulltext Catalog XML schema collection
Certificate
Asymmetric Key
Symmetric Key
Contact
Schema Assemblies
Schemas

Permissions

The permissions link principals with securables. For example, a SQL LOGIN (the  principal) needs to CREATE (the permission) databases (the securable). Together, these three elements represent a complete security assignment.

Managing Permissions

  1. A GRANT of a permission removes any REVOKE or DENY on a securable. For example, if a table has SELECT permission denied on it and then the SELECT permission is granted, the DENY permission will then be removed on that table.
  2. DENY and REVOKE remove any GRANT permission on a securable. REVOKE removes any GRANT or DENY permission on a securable.
  3. Permissions denied at a higher scope in the security model override grants on that permission at a lower scope. Keep in mind that the security model has the server scope at the highest level, followed by database and schema. So, if INSERT permission is denied on tables at the database level, and INSERT on a specific table in that database is granted at the schema level, the result is that INSERT is denied on all tables. In this example, a database-level DENY overrides any GRANT at the lower schema level.
  4. Permissions granted at a higher scope in the security model are overridden by a DENY permission at a lower level. For example, if INSERT permission is granted on all tables at the database scope, and INSERT is denied on a specific table in the database (schema scope), INSERT is then denied on that specific table.

Statement permissions have nothing to do with the actual data; they allow users to create the structure that holds the data.

  1. Create Database
  2. Create Table
  3. Create View
  4. Create Procedure
  5. Create Index
  6. Create Rule
  7. Create Default

The second type of permissions is object permissions, which control how users work with the actual data.

Object Permission Description
Control This permission gives the principal ownership-like capabilities on the object and all objects under it in the hierarchy. For example, if you grant a user Control permission on the database, then the user has Control permission on all the objects in the database, such as tables and views.
Alter This permission allows users to create, alter, or drop the securable and any object under it in the hierarchy. The only property the user can’t change is ownership.
Take Ownership This allows the user to take ownership of an object.
Impersonate This permission allows one login or user to impersonate another.
Create As the name implies, this permission lets a user create objects.
View Definition This permission allows users to see the Transact-SQL syntax that was used to create the object being secured.
Select When granted, this permission allows users to read data from the table or view. When granted at the column level, it lets users read from a single column.
Insert This permission allows users to insert new rows into a table.
Update This permission lets users modify existing data in a table but not add new rows to or delete existing rows from a table. When this permission is granted on a column, users can modify data in that single column.
Delete This permission allows users to remove rows from a table.
References Tables can be linked together on a common column with a foreign-key relationship, which is designed to protect data across tables. When two tables are linked with a foreign key, this permission allows the user to select data from the primary table without having Select permission on the foreign table.
Execute This permission allows users to execute the stored procedure where the permission is applied.
All the permissions in SQL Server can exist in one of three states:
Grant Granting allows users to use a specific permission. For instance, if you grant SmithB Select permission on a table, then SmithB can read the data within. You know a permission has been granted when the Allow check box is selected next to the permission in the permissions list
Revoke A revoked permission isn’t specifically granted, but a user can inherit the permission if it has been granted to another role of which they are a member. That is, if you revoke the Select permission from SmithB, then SmithB can’t use it. If, however, SmithB is a member of a role that has been granted Select permission, SmithB can read the data just as if SmithB had the Select permission. A permission is revoked when neither Allow nor Deny boxes are selected next to a permission.
Deny If you deny a permission, the user doesn’t get the permission—no matter what. If you deny SmithB Select permission on a table, even if SmithB is a member of a role with Select permission, then SmithB can’t read the data. You know a permission has been denied when the Deny check box is selected next to the permission in the permissions list.

SQL Server Security Principals

August 8th, 2008 Posted in SQL Server, Security  No Comments »

Principals:

Principals are the entities that request security to SQL Server resources.

Scope Principals
SQL Server Level SQL Server Login
Windows Level Local user, Local group, Domain user, Domain group
Database Level Database User, Database Role, Application Role

Default Logins

  1. Every principal that is granted security to SQL Server must have an associated login.
  2. The login provides access to SQL Server and can be associated with principals that are scoped at the Windows and server levels
  3. These logins can be associated with Windows accounts, Windows groups, or SQL Server logins
  4. Logins are stored in the master database and can be granted permission to resources that are scoped at the server level.
  5. Logins provide the initial permission needed to access a SQL Server instance and allow you to grant access to the related databases.
  6. Permissions to specific database resources must be granted via a database user.
  7. The important thing to remember is that logins and users are directly related to each other but are different entities. It is possible to create a new login without creating an associated database user, but a new database user must have an associated login.

1. SA account

  1. The SA account is a SQL LOGIN that is assigned to the SysAdmin fixed-server role.
  2. The SA account cannot be removed, and it can always be used to gain access to SQL Server.
  3. The SA account should always have a strong password to prevent malicious attacks, and it should be used only by database administrators.

2. BUILTIN\Administrators login

  1. The login is made a member of the SysAdmin fixed-server role
  2. It is a windows group that corresponds to the local administrators group for the machine that SQL Server is running on.

3. NT AUTHORITY\SYSTEM login

  1. This account is related to the local system account that SQL Server services can run under.
  2. It is also added as a member of the sysadmin fixed-server role.
  3. This account can also be removed if the SQL Server services are not running with the local system account. This should be done with caution, however, because it can affect applications such as Reporting Services.

To better understand logins, you can look at the sys.server_principals catalog view. This view contains a row for every server-level principal, including each server login. The following example selects from this view and displays the results:

select left(name,25) name, type, type_desc
from sys.server_principals AS log
WHERE (log.type in (‘U’, ‘G’, ‘S’, ‘R’))
order by 3,1

Default Users

  1. DBO- default owner ( when login by administrator)
  2. Guest – ( drop it recommended )
  3. Information_Schema
  4. Sys -

dbo User

  1. The dbo user is the database owner and cannot be deleted from the database.
  2. Members of the Sysadmin server role are mapped to the dbo user in each database, which allows them to administer all databases.
  3. Objects owned by dbo that are part of the dbo schema can be referenced by the object name alone. When an object is referenced without a schema name, SQL Server first looks for the object in the default schema for the user that is connected. If the object is not in the user’s default schema, the object is retrieved from the dbo schema. Users can have a default schema that is set to dbo.

guest User

  1. The guest user is created by default in each database when the database is created. This account allows users that do not have a user account in the database to access the database.
  2. By defa-ult, the guest user does not have permission to connect to the database. To allow logins without a specific user account to connect to the database, you need to grant
  3. GRANT CONNECT TO GUEST
  4. The guest account is a special account and does not have an associated login. You can change the access for the guest account by using T-SQL commands instead.
  5. EXEC sp_addrolemember N’db_datareader’, N’guest’

INFORMATION_SCHEMA User

The INFORMATION_SCHEMA user owns all the information schema views that are installed in each database. it cannot be dropped from the database.

sys User

The sys account gives users access to system objects such as system tables, system views, extended stored procedures, and other objects that are part of the system catalog. The sys user owns these objects. Like the INFORMATION_SCHEMA user, it cannot be dropped from the database.
List All Users

  SELECT  left(u.name,25) AS [Name], type, left(type_desc,15) as type_desc
  FROM  sys.database_principals AS u
  WHERE  (u.type in (‘U’, ‘S’, ‘G’)) ORDER BY 1

View all object by user

  SELECT name, object_id,  schema_id, type_desc
  FROM sys.all_objects
  WHERE  OBJECTPROPERTYEX(object_id, N'OwnerId') = USER_ID(N'sys')
  ORDER BY 1

User/Schema Separation

It is a collection of database objects that one user owns and that forms a single namespace. A single namespace is one in which each object name is unique and there are no duplicates.

ROLES

Permissions are applied to a role, and then members are added to the role. Any member of the role has all the permissions that the role has.

SQL Server has the following three types of roles:
1.Fixed-server and fixed-database roles
These roles are installed by default and have a predefined set of permissions.
2.User-defined roles

These roles are created in each database, with a custom set of permissions for each set of users assigned to it.

3.Application roles

These roles are a special roles that can be used to manage database access for an application.

Fixed-Server Roles ( Server levelsecurables )

Role Permission
Bulkadmin Allowed to run the BULK INSERT statement.
Dbcreator Allowed to CREATE, ALTER, DROP, and RESTORE any database.
Diskadmin Allowed to manage disk files that are used by SQL Server.
Processadmin Allowed to terminate SQL Server processes.
Securityadmin Allowed to GRANT, DENY, and REVOKE permissions for logins at the server and database levels. Members of this role can reset passwords for SQL Server logins
Serveradmin Allowed to change serverwide configuration properties and shut down the server, if needed.
Setupadmin Allowed to add and remove linked servers and execute some system stored procedures.
Sysadmin Allowed to perform any activity in the server.

Fixed-Database Roles

Role Permission
db_accessadmin Allowed to add or remove database access for logins.
db_backupoperator Allowed to back up the database
db_datareader Allowed to read all user table data.
db_datawriter Allowed to change the data in all user tables.
db_ddladmin Allowed to run any Data Definition Language (DDL) command against the database. This includes commands to create, alter, and drop database objects.
db_denydatareader Denied the right to read all user table data.
db_denydatawriter Denied the right to change the data in any of the user tables.
db_owner Allowed to perform any action on the database. Members of the sysadmin fixed–server role are mapped to this database role
db_securityadmin Allowed to manage permissions for database users, including membership in roles.

The public Role

  1. The public role is a special database role that is like a fixed-database role except that its permissions are not fixed. The permissions for this role can be altered.
  2. Every user in a database is automatically made a member of the public role and in turn receives any permissions that have been granted to the public role. Database users cannot be removed from the public role.
  3. The public role is similar in function to the guest user that is installed by default in each database. The difference is that the permissions granted to the guest user are used by any login that does not have a user account in the database. In this case, the login is allowed to enter the database via the guest account. In the case of the public role, the login has been added as a user of the database and in turn picks up any permissions that have been granted to the public role.

To view the permissions associated with the public role

SELECT top 5 g.name,  object_name(major_id) as ‘Object’, permission_name
from  sys.database_permissions p
join  sys.database_principals g
on p.grantee_principal_id  = g.principal_id
and g.name = ‘public’
order by 1,2

This SELECT utilizes two catalog views that contain security information. The SELECT returns only the first five permissions for the public role, but the TOP clause can be removed to return all the permissions.

Application Role

To obtain the permissions associated with the role, the connection must set the role and supply the password.

This is done using the stored procedure sp_setapprole. You set the role to the sales application role (with the password PassW0rd) as follows:

   EXEC sp_setapprole ‘sales’,  ‘PassW0rd’

You can also encrypt the password:

  EXEC sp_setapprole ‘sales’,  {ENCRYPT N ‘ PassW0rd’}, ‘odbc’

SQL Server Security

August 2nd, 2008 Posted in SQL Server, Security  No Comments »

Principals: Principals are the entities that request security to SQL Server resources.

Securables - Securables are the SQL Server resources that permissions can be granted to.

Permissions - The permissions link principals with securables. For example, a SQL LOGIN (the  principal) needs to CREATE (the permission) databases (the securable). Together, these three elements represent a complete security assignment.

SA account

  1. The SA account is a SQL LOGIN that is assigned to the SysAdmin fixed-server role.
  2. The SA account cannot be removed, and it can always be used to gain access to SQL Server.
  3. The SA account should always have a strong password to prevent malicious attacks, and it should be used only by database administrators.

BUILTIN\Administrators login

  1. The login is made a member of the SysAdmin fixed-server role
  2. It is a windows group that corresponds to the local administrators group for the machine that SQL Server is running on.

NT AUTHORITY\SYSTEM login

  1. This account is related to the local system account that SQL Server services can run under.
  2. It is also added as a member of the sysadmin fixed-server role.
  3. This account can also be removed if the SQL Server services are not running with the local system account. This should be done with caution, however, because it can affect applications such as Reporting Services.

dbo User

  1. The dbo user is the database owner and cannot be deleted from the database.
  2. Members of the Sysadmin server role are mapped to the dbo user in each database, which allows them to administer all databases.
  3. Objects owned by dbo that are part of the dbo schema can be referenced by the object name alone. When an object is referenced without a schema name, SQL Server first looks for the object in the default schema for the user that is connected. If the object is not in the user’s default schema, the object is retrieved from the dbo schema. Users can have a default schema that is set to dbo.

guest User

  1. The guest user is created by default in each database when the database is created. This account allows users that do not have a user account in the database to access the database.
  2. By defa-ult, the guest user does not have permission to connect to the database. To allow logins without a specific user account to connect to the database, you need to grant
  3. GRANT CONNECT TO GUEST
  4. The guest account is a special account and does not have an associated login. You can change the access for the guest account by using T-SQL commands instead.
  5. EXEC sp_addrolemember N’db_datareader’, N’guest’

The INFORMATION_SCHEMA User

The INFORMATION_SCHEMA user owns all the information schema views that are installed in each database. it cannot be dropped from the database.

The sys User

The sys account gives users access to system objects such as system tables, system views, extended stored procedures, and other objects that are part of the system catalog. The sys user owns these objects. Like the INFORMATION_SCHEMA user, it cannot be dropped from the database.

List All Users

SELECT left(u.name,25) AS [Name], type, left(type_desc,15) as type_desc

FROM sys.database_principals AS u

WHERE (u.type in (‘U’, ‘S’, ‘G’)) ORDER BY 1

View all object by user

SELECT name, object_id, schema_id, type_desc

FROM sys.all_objects

WHERE OBJECTPROPERTYEX(object_id, N’OwnerId’) = USER_ID(N’sys’)

ORDER BY 1

User/Schema Separation

It is a collection of database objects that one user owns and that forms a single namespace. A single namespace is one in which each object name is unique and there are no duplicates.

ROLES

Permissions are applied to a role, and then members are added to the role. Any member of the role has all the permissions that the role has.

SQL Server has the following three types of roles:

1.Fixed-server and fixed-database roles

These roles are installed by default and have a predefined set of permissions.

2.User-defined roles

These roles are created in each database, with a custom set of permissions for each set of users assigned to it.

3.Application roles

These roles are a special roles that can be used to manage database access for an application.

Fixed-Server Roles ( Server levelsecurables )

ROLE               PERMISSION

Bulkadmin Allowed to run the BULK INSERT statement.

Dbcreator Allowed to CREATE, ALTER, DROP, and RESTORE any database.

Diskadmin Allowed to manage disk files that are used by SQL Server.

Processadmin Allowed to terminate SQL Server processes.

Securityadmin Allowed to GRANT, DENY, and REVOKE permissions for logins at the server and                                   database levels. Members of this role can reset passwords for SQL Server logins

Serveradmin Allowed to change serverwide configuration properties and shut down the server, if                                 needed.

Setupadmin Allowed to add and remove linked servers and execute some system stored procedures.

Sysadmin Allowed to perform any activity in the server.

Fixed-Database Roles

ROLE                           PERMISSION

db_accessadmin Allowed to add or remove database access for logins.

db_backupoperator Allowed to back up the database.

db_datareader Allowed to read all user table data.

db_datawriter Allowed to change the data in all user tables.

db_ddladmin Allowed to run any Data Definition Language (DDL) command against the                                               database. This includes commands to create, alter, and drop database objects.

db_denydatareader Denied the right to read all user table data.

db_denydatawriter Denied the right to change the data in any of the user tables.

db_owner Allowed to perform any action on the database. Members of the sysadmin fixed–                                               server role are mapped to this database role.

db_securityadmin Allowed to manage permissions for database users, including

membership in roles.

The public Role

  1. The public role is a special database role that is like a fixed-database role except that its permissions are not fixed. The permissions for this role can be altered.
  2. Every user in a database is automatically made a member of the public role and in turn receives any permissions that have been granted to the public role. Database users cannot be removed from the public role.
  3. The public role is similar in function to the guest user that is installed by default in each database. The difference is that the permissions granted to the guest user are used by any login that does not have a user account in the database. In this case, the login is allowed to enter the database via the guest account. In the case of the public role, the login has been added as a user of the database and in turn picks up any permissions that have been granted to the public role.

To view the permissions associated with the public role,

SELECT top 5 g.name, object_name(major_id) as ‘Object’, permission_name

from sys.database_permissions p

join sys.database_principals g

on p.grantee_principal_id = g.principal_id

and g.name = ‘public’

order by 1,2

This SELECT utilizes two catalog views that contain security information. The SELECT returns only the first five permissions for the public role, but the TOP clause can be removed to return all the permissions.

Application Role

To obtain the permissions associated with the role, the connection must set the role and supply the password.

This is done using the stored procedure sp_setapprole. You set the role to the sales application role (with the password PassW0rd) as follows:

EXEC sp_setapprole ‘sales’, ‘PassW0rd’

You can also encrypt the password:

EXEC sp_setapprole ‘sales’, {ENCRYPT N ‘ PassW0rd’}, ‘odbc’

Managing Permissions

  1. A GRANT of a permission removes any REVOKE or DENY on a securable. For example, if a table has SELECT permission denied on it and then the SELECT permission is granted, the DENY permission will then be removed on that table.
  2. DENY and REVOKE remove any GRANT permission on a securable. REVOKE removes any GRANT or DENY permission on a securable.
  3. Permissions denied at a higher scope in the security model override grants on that permission at a lower scope. Keep in mind that the security model has the server scope at the highest level, followed by database and schema. So, if INSERT permission is denied on tables at the database level, and INSERT on a specific table in that database is granted at the schema level, the result is that INSERT is denied on all tables. In this example, a database-level DENY overrides any GRANT at the lower schema level.
  4. Permissions granted at a higher scope in the security model are overridden by a DENY permission at a lower level. For example, if INSERT permission is granted on all tables at the database scope, and INSERT is denied on a specific table in the database (schema scope), INSERT is then denied on that specific table.

Statement permissions have nothing to do with the actual data; they allow users to create the structure that holds the data.

  1. Create Database
  2. Create Table
  3. Create View
  4. Create Procedure
  5. Create Index
  6. Create Rule
  7. Create Default

The second type of permissions is object permissions, which control how users work with the actual data.

Control This permission gives the principal ownership-like capabilities on the object and all objects under it in the hierarchy. For example, if you grant a user Control permission on the database, then the user has Control permission on all the objects in the database, such as tables and views.

Alter This permission allows users to create, alter, or drop the securable and any object under it in the hierarchy. The only property the user can’t change is ownership.

Take Ownership This allows the user to take ownership of an object.

Impersonate This permission allows one login or user to impersonate another.

Create As the name implies, this permission lets a user create objects.

View Definition This permission allows users to see the Transact-SQL syntax that was used to create the object being secured.

Select When granted, this permission allows users to read data from the table or view. When granted at the column level, it lets users read from a single column.

Insert This permission allows users to insert new rows into a table.

Update This permission lets users modify existing data in a table but not add new rows to or delete existing rows from a table. When this permission is granted on a column, users can modify data in that single column.

Delete This permission allows users to remove rows from a table.

References Tables can be linked together on a common column with a foreign-key relationship, which is designed to protect data across tables. When two tables are linked with a foreign key, this permission allows the user to select data from the primary table without having Select permission on the foreign table.

Execute This permission allows users to execute the stored procedure where the permission is applied.

All the permissions in SQL Server can exist in one of three states:

Grant Granting allows users to use a specific permission. For instance, if you grant SmithB Select permission on a table, then SmithB can read the data within. You know a permission has been granted when the Allow check box is selected next to the permission in the permissions list.

Revoke A revoked permission isn’t specifically granted, but a user can inherit the permission if it has been granted to another role of which they are a member. That is, if you revoke the Select permission from SmithB, then SmithB can’t use it. If, however, SmithB is a member of a role that has been granted Select permission, SmithB can read the data just as if SmithB had the Select permission. A permission is revoked when neither Allow nor Deny boxes are selected next to a permission.

Deny If you deny a permission, the user doesn’t get the permission—no matter what. If you deny SmithB Select permission on a table, even if SmithB is a member of a role with Select permission, then SmithB can’t read the data. You know a permission has been denied when the Deny check box is selected next to the permission in the permissions list.

Tips:

  1. Every principal that is granted security to SQL Server must have an associated login.
  2. Logins are stored in Master database.
  3. It is possible to create a new login without creating an associated database user, but a new database user must have an associated login.
  4. A login is used for user authentication ( connect to SQL Server)
  5. A database user account is used for database access and permissions validation (database)
  6. sa, builtin\administrators, and NT authority\system) are logins that are installed by default at installation time.
  7. Dbo,guest,Information_schema and sys are database users that have been created by default at installation time.

PRACTICAL

Server Level Security

LOGIN

  1. Registered Servers ( alt + ctrl + G)
  2. Right click on Database Engine and Create group.
  3. Add registered server into created groups.
  4. Right click on Register server and connect to object explorer
  5. Create window user  & associated window group.(computer Management)
  6. Create window login – wLogin ( Management Studio )
  7. General Tab
  8. Window login ( active directory )
  9. Default database
  10. Enforce password policy  ( only in SQL login )
  11. Server Roles
  12. Select Server role default is Public ( unelectable)
  13. User Mapping
  14. Select databases
  15. Select Database roles
  16. Select Server Level Securable
  17. Grant Permissions
  18. Status
  19. Grant permission to database Engine
  20. Enable / Disable Login

SERVER ROLES

  1. Add members to any server roles

CREDENTIALS

  1. You can map window credential to SQL authentication user to access any kind of resource  (file system )outside SQL Server.

Database level Security

SCHEMA

  1. Right click on Schema and select New and enter Name
  2. Select Schema owner ( users, database roles, application roles )
  3. To apply Permission to object in schema add objects into it
  4. Create table with associated schema

USERS

  1. Create User named  sLogin associated with login
  2. Default schema ( can’t assign default schema in window authenticated user )
  3. Owned schema by this user ( schema has only one owner )cant unselect
  4. Database roles by this user
  5. Securable
  6. Add object associated with schema and grant permissions
  7. Extend properties ( for documention)

CBT Security Video 14:30 à 36

Creating a Windows Login

Task 1.17 Creating a Standard Login

Task 1.18 Assigning Logins to Fixed Server Roles

Task 1.19 creating a Database User Mapping

Task 1.20 Assigning User Mappings to Fixed Database Roles

Task 1.21 Creating a Custom Database Role

Task 1.22 Creating an application Role

Task 1.23 Assigning Permissions

Users, Roles and groups

Managing schemas

DDL Triggers

Default Users

  1. DBO- default owner ( when login by administrator)
  2. Guest – ( drop it recommended )
  3. Information_Schema
  4. Sys -

User mapping

Every single user has public role.  We can’t un-select it.

Grant privilege to role à grant that role to individual user

//orfan user

Exec sp_addrolemember ‘db_datawriter’ , ‘johnson\joe’

Exec sp_changeuser

Users, Server Roles,

User Mapping-database role-default schema

, Securables, Status

Practice:

Create Schemaà

create Database role –  (a ) select default schema created, (b)Members to this roles

Application role – default created schema , add securables

——————————

DDL Triggers

Monitor most DDL activity

  1. Prevent unauthorized usage
  2. Audit DDL

2 Scope

  1. Server
  2. Database
Create trigger my_ddl_trig
  on database
  for ddl_database_level_events as
  ----    8-16
  if datepart(hour,getDate())<8 or
  datepart(hour,getDate())>17
  print ‘cannot perform ddl outside of normal business  hours’
rollback

SQL Server Indexes

July 25th, 2008 Posted in Indexes, SQL Server  No Comments »

IMPLEMENTING INDEXES
INTRODUCTION TO INDEXES
Indexes

  1. Indexes improve query performance by reducing I/O operations ( select, update, delete )
  2. Indexes are built on one or more columns in a table or  view ( keys)
  3. Indexes are automatically created for primary key and unique constraints

Index Types

  1. Clustered index ( like phone book ) –binary tree
  2. Leaf nodes contains actual data pages
  3. Root, intermediate, look
  4. Data sorted and stored based on index key
  5. Non clustaered index binary tree
  6. Intermediate nodes contain pointers to actual data pages
  7. Data not sorted based on key
  8. Unique, included, full text, xml

Index Guidelines- query optimizer
Non-Clustered

  1. Queries that do not return large data sets
  2. Queries that return exact matching ( where )
  3. Covered querry
  4. Columns with high degree of uniqueness (1-1 relationship)
  5. Group by columns

Clustered

  1. Queries that return large data sets
  2. Qeures that return ranges
  3. Columns with a high degree of uniqueness
  4. Foreign key columns
  5. Group by and order by

Database

  1. Avoid on indexing  heavily updated tasks
  2. Use many indexes on tables with little to no data modifications
  3. Avoid indexing small tables

Practical WORKING WITH INDEXES

  1. Primary key creates clustered index
  2. Tables à Indexes à right click and New index
  3. Fill factor work with leaf level node while pad index works with intermediate level node
  4. Covered index–  cover all columns in index=add non-key column into index

MAINTAINING & OPTIMIZING INDEXES
1)
Index Property à fragmentation à if total fragmentation <30% re organize( ), if >30% rebuild ( drop and created )
2)Database Engine tuning advisor run and see recommendation
3) SQL Profiler
Display estimated query plan, select and execute

Display actual query plan, select and execute

CLUSTERED INDEX , Non Cluster Idnex, unique Index ( just check box)
Tables –TableAà Indexà Right click and New
Optons: left all default except
Set fill factor specify how full sql server should make leave level of each index page when creating the index Pad Index specify space to leave open on each page in intermediate levels of the index Allow Online Indexing
—Creating covered indexes
Include include columns ( non covered key or non-key files)
Maintaining Index – rebuild or re organize

Introduction to Joins

July 14th, 2008 Posted in Database Design, Databases, SQL Server, T-SQL  No Comments »

Joins

The types of joins that SQL Server supports are listed in Table 4-3.

Type of join Description
Inner joins Retrieves only data that exists in both tables based on the JOIN. INNER JOIN is frequently shorteded to just JOIN.
Outer Joins Inner Joins allow us to pull data that exists in both tables, but sometime we want to pull all the data from one of the tables, in addition to what matches in both tables. These a-re referred as to as Outer Joins
Left outer joins Retrieves all data in left table, and only data that exists in the right table based on the JOIN.
Right outer join Retrieves all data in right table, and only data that exists in the left table based on the JOIN.
Full join (full outer join) Retrieves all data in both tables.
Cross joins Creates a Cartesian product of the tables. Used to create sample databases with large volumes of data without too much effort.
Self-join Joining a table to itself. This is sometimes required when retrieving data from a table that references the table (such as ManagerID of an Employee also being in the Employee table as EmployeeID).

INNER JOINS

SELECT Production.Product.Name,
	Production.Product.ProductNumber,
	Production.ProductModel.Name as 'Model Name'
FROM
Production.ProductModel Inner join Production.Product
ON
Production.ProductModel.ProductModelID=Production.Product.ProductModelID

OUTER JOINS

Once more than two tables are involved in the query, things get a bit more complicated. When a table is joined to the RIGHT table, a LEFT OUTER JOIN must be used. That is because the NULL rows from the RIGHT table will not match any rows on the new table. An INNER JOIN causes the non-matching rows to be eliminated from the results. If the Sales.SalesOrderDetail table is joined to the Sales.SalesOrderHeader table and an INNER JOIN is used, none of the customers without orders will show up. NULL cannot be joined to any value, not even NULL.

To illustrate this point, when I add the Sales.SalesOrderDetail table to one of the previous queries that checked for customers without orders, I get back no rows at all.

SELECT c.CustomerID, s.SalesOrderID, d.SalesOrderDetailID
FROM Sales.Customer c
LEFT OUTER JOIN Sales.SalesOrderHeader s ON c.CustomerID = s.CustomerID
INNER JOIN Sales.SalesOrderDetail d ON s.SalesOrderID = d.SalesOrderID
WHERE s.SalesOrderID IS NULL

To get correct results, change the INNER JOIN to a LEFT JOIN.

SELECT c.CustomerID, s.SalesOrderID, d.SalesOrderDetailID
FROM Sales.Customer c
LEFT OUTER JOIN Sales.SalesOrderHeader s ON c.CustomerID = s.CustomerID
LEFT OUTER JOIN Sales.SalesOrderDetail d ON s.SalesOrderID = d.SalesOrderID
WHERE s.SalesOrderID IS NULL

What about additional tables joined to Sales.Customer, the table on the left? Must outer joins be used? If it is possible that there are some rows without matches, it must be an outer join to guarantee that no results are lost. The Sales.Customer table has a foreign key pointing to the Sales.SalesTerritory table. Every customer’s territory ID must match a valid value in Sales.SalesTerritory. This query returns 66 rows as expected because it is impossible to eliminate any customers by joining to Sales.SalesTerritory:

SELECT c.CustomerID, s.SalesOrderID, t.Name
FROM Sales.Customer c
LEFT OUTER JOIN Sales.SalesOrderHeader s ON c.CustomerID = s.CustomerID
INNER JOIN Sales.SalesTerritory t ON c.TerritoryID = t.TerritoryID
WHERE SalesOrderID IS NULL

Sales.SalesTerritory is the primary key table; every customer must match a valid territory. If you wanted to write a query that listed all territories, even those that had no customers, an outer join will be used. This time, Sales.Customers is on the right side of the join.

SELECT t.Name, CustomerID  FROM Sales.SalesTerritory t
LEFT OUTER JOIN Sales.Customer c ON t.TerritoryID = c.TerritoryID

Cross Join

Many SQL books and tutorials recommend that you “avoid cross joins” or “beware of Cartesian products” when writing your SELECT statements, which occur when you don’t express joins between your tables.

SELECT S.Store, P.Product
FROM Stores S
CROSS JOIN Products P

Self Join

A table can be joined to itself in a self-join. For example, you can use a self-join to find the products that are supplied by more than one vendor.

USE AdventureWorks;
GO
SELECT DISTINCT pv1.ProductID, pv1.VendorID
FROM Purchasing.ProductVendor pv1
INNER JOIN Purchasing.ProductVendor pv2 ON pv1.ProductID = pv2.ProductID
    AND pv1.VendorID <> pv2.VendorID
ORDER BY pv1.ProductID

Date/Time Conversions Using SQL Server

July 8th, 2008 Posted in SQL Server, T-SQL  No Comments »

SQL Server provides a number of options you can use to format a date/time string. One of the first considerations is the actual date/time needed. The most common is the current date/time using getdate(). This provides the current date and time according to the server providing the date and time. If a universal date/time is needed, then getutcdate() should be used. To change the format of the date, you convert the requested date to a string and specify the format number corresponding to the format needed. Below is a list of formats and an example of the output:

Date/Time Conversions Using SQL Server

select convert(varchar,Content.created,111) as created from Content

DATE FORMATS
Format # Query (current date: 12/30/2006) Sample
1 select convert(varchar, getdate(), 1) 12/30/06
2 select convert(varchar, getdate(), 2) 06.12.30
3 select convert(varchar, getdate(), 3) 30/12/06
4 select convert(varchar, getdate(), 4) 30.12.06
5 select convert(varchar, getdate(), 5) 30-12-06
6 select convert(varchar, getdate(), 6) 30 Dec 06
7 select convert(varchar, getdate(), 7) Dec 30, 06
10 select convert(varchar, getdate(), 10) 12-30-06
11 select convert(varchar, getdate(), 11) 06/12/30
101 select convert(varchar, getdate(), 101) 12/30/2006
102 select convert(varchar, getdate(), 102) 2006.12.30
103 select convert(varchar, getdate(), 103) 30/12/2006
104 select convert(varchar, getdate(), 104) 30.12.2006
105 select convert(varchar, getdate(), 105) 30-12-2006
106 select convert(varchar, getdate(), 106) 30 Dec 2006
107 select convert(varchar, getdate(), 107) Dec 30, 2006
110 select convert(varchar, getdate(), 110) 12-30-2006
111 select convert(varchar, getdate(), 111) 2006/12/30
     
TIME FORMATS
8 or 108 select convert(varchar, getdate(), 8) 00:38:54
9 or 109 select convert(varchar, getdate(), 9) Dec 30 2006 12:38:54:840AM
14 or 114 select convert(varchar, getdate(), 14) 00:38:54:840

You can also format the date or time without dividing characters, as well as concatenate the date and time string:

Sample statement Output
select replace(convert(varchar, getdate(),101),’/',”) 12302006
select replace(convert(varchar, getdate(),101),’/',”) + replace(convert(varchar, getdate(),108),’:',”) 12302006004426

SQL Server T-SQL

July 3rd, 2008 Posted in SQL Server, T-SQL  No Comments »

T-SQL

INTRODUCTION TO T-SQL

DML

  1. Select, Insert , Update, Delete

DDL

  1. Create, alter  & drop

Common T-SQL

  1. Variables ( temp data storage
  2. Functions (built-in operations
  3. Control of flow ( decision making constructs )
  4. Syntax
  5. Coding conventions

USING DML STATEMENTS

  1. Where
  2. Like , <
  3. Order by
  4.  

WORKING WITH T-SQL

INTRODUCTION TO DDL

SQL Server Views

June 28th, 2008 Posted in SQL Server, Views  No Comments »

INTORDUCTION TO VIEWS

View

  1. Views are virtual tables defined by a query and generated when called.

Types of Views

  1. Standard Views
  2. Combine & filtering data from one or more tables
  3. Simplifies data manipulations & results
  4. Indeed Views
  5. view within a clustered index
  6. indeed views are computed & physically stored  in the database
  7. Partitioned Views
  8. Combines horizontally partitioned data from member tables across one or more servers.
  9. Local portioned views combine data from tables On the same server
  10. Distributed partitioned views combine data from tables across servers.

View Usage

Standard views

  1. Simplify results by focusing on specific data
  2. Simplify security by controlling access through views rather than tables
  3. Provide backward compatibility during schema changes

Indexed Views

  1. Great for complex queries which return large results and require heavy processing
  2. Other queries can benefit from the index on a view
  3. Updates are reflected in the stored data.

Partitioned Views

  1. Scale our processing by portioning tables into multiple member tables.

CREATING & MODIFYING VIEWS

WORKING WITH VIEWS

PRACTICE

1)

Create view named  as SQL Query ( standard view )

2)

Create view Named with SchemaBinding as SQLQuery ( INDEX VIEW )

Go

Create Unique clustered Index IX_AllTime

On Sales.vixAllTime(name)

3) Distributed Partitioned View

1. Create New Table1 on Server 1 , check constraint on portioning column

2.  insert data from original table to Table1

3. Create New Table1 on  Server2, check constraint on portioning colum

4. import data from Table1 from its original table1

5. Create Link Server  on both server ( be made using login’s current security context )

6.  Create view Sales on Server 1 as select query from Server 1 Union All select query from Server2

7. Create same view on server 2

Modifying Data Via View

—creating a Standard Views

Create View vABC

As

Select Statement

//access

Select * from vABC

—Creating Indexed Views

  1. It binds this view with the table, so you cant change based table
  2. Count_big(*) required
  3. Create unique clustered index
  4. If using group by then make index on this field

Create view vABC

With schemabinding

As

Select name, sum(qty),

SQL Server User Defined Functions

June 21st, 2008 Posted in SQL Server, User Defined Functions  No Comments »

INTRODUCTION TO USER DEFINED FUNCTION

User Defined Functions

  • Module code component stored in database
  • Perform action & return results
  • Results can be single value ( scalar ) or a results set ( table )
  • Can accept parameters

Types of Functions

  • Scalar UDF’s – Return single value of desired type
  • Table-valued UDF’s – Return results as a table data type
  • Built in functions- System code  T-SQL function

UDF Benefits

  • Modular programming
  • Reduce network traffic
  • Fast execution
  • Can be used within queries

GUIDE LINES
General UDF Usage

  • Within DML statements
  • As defaults on columns like getDate()
  • As check constraints on columns
  • Parameterize a view
  • Replace a stored procedure that return single result set

Table Valued UDF

  • Multi statement definition
  • Reference like tables & views
  • More flexible than views ( T-SQL Logic)
  • Easier to use than stored procedure

Inline UDF’s

  • Single statement definition
  • Can have scalar and table-valued inline UDF’s
  • Scalar UDF’ – replace single return value stored procedure

CREATING & USING USER DEFINED FUNCTIONS

  • Create scalar function and use them in query by mentioning namespace
  • Data access scalar function
  • Inline table valued functions
  • Parameterized view from inline table-values function ( select * from view)
  • When exits….. where … then case statement
  • Before as “with encryption”. Cant modify encrypted functions

Creating Scalar User-Defined Functions
A scalar user-defined function accepts zero or more parameters, and returns a single value. Scalar  UDFs are often used for converting or  translating a current value to a new value, or performing other sophisticated lookups based on specific parameters. Scalar functions can   be used within search, column, and join expressions.

–General Scalar Function
CREATE FUNCTION ufnFormatCurrency(@Amount Money)
Returns VarChar(100)
AS
BEGIN
Return ‘$’ + Convert(VarChar, CONVERT(Money, @Amount),1);
–may b database select statement
End
–Usage
Select
soh.SubTotal as Original,
dbo.ufnFormatCurrency(soh.SubTotal) as SubTotal
from
Sales.SalesOrderHeader soh

Table-Valued Functions

  • A table-valued user-defined function returns a row-set instead of a single scalar value.
  • You can invoke a table-valued function in the FROM clause of a SELECT statement
  • A table-valued function specifies the keyword TABLE in its RETURNS clause.
  • Table-valued functions are of two types: inline and multi-statement.
  • The two types of table-valued functions return the same thing, and they are also invoked the same way. The only real difference between them is the way the function is written to return the row-set.

–Creating Inline Table-Valued Function
Create Function Sales.ufnStoreYTDSales()
Returns Table
as
Return
&n0123456789012345678901234567890123456789

Default Parameter & COALESCE , Error Trapping

June 14th, 2008 Posted in SQL Server, Stored Procedure  No Comments »

return specified record or all

Default Parameter & COALESCE

Exec ABC default, 5 —– two parameter first is default and second is supplied

COALESCE (Transact-SQL)

Returns the first non-null expression among its arguments.

--Get  result with parameter else return all
  create PROCEDURE  ABC
  @ID int =null;
  AS
  BEGIN
   select * from Production.Product as p
  where
  p.ProductID= coalesce (@ID  ,p.ProductID)
  END
  GO
  exec ABC
  exec ABC 3
--Trapping for errors using Try.....Catch
BEGIN TRY
		EXECUTE spDoesNotExist
END TRY
BEGIN CATCH
		SELECT
		ERROR_LINE() AS ErrorLine,
		ERROR_NUMBER() as ErrorNumber,
		ERROR_MESSAGE() as ErrorMessage,
		ERROR_SEVERITY() as ErrorSeverity,
		ERROR_STATE() as ErrorState
END CATCH

Executing Stored Procedures Automatically at SQL Server

June 7th, 2008 Posted in SQL Server, Stored Procedure  No Comments »

Executing Stored Procedures Automatically at SQL Server

Startup

You can designate a stored procedure to be executed whenever the SQL Server service is started. You

may wish to do this to perform any cleanup tasks your SQL Server instance requires (for example,

documenting when the service started, or clearing out work tables).

This automatic execution of a stored procedure is achieved using the sp_procoption system

stored procedure. The command looks like it takes several different options, but in SQL Server 2005,

it really only performs a single task, which is setting a stored procedure to execute automatically when

the SQL Server service restarts.

In this example, a stored procedure is set to execute automatically whenever SQL Server is started.

First, the database context is set to the master database (which is the only place that auto-executable

stored procedures can be placed):

  USE MASTER
  GO
  Next, for the example, a startup logging table is created:
  CREATE TABLE dbo.SQLStartupLog
  (SQLStartupLogID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
  StartupDateTime datetime NOT NULL)
  GO
  Now, a new stored procedure is created to insert a value into the new table (so you can see
  whenever SQL Server was restarted using the table):
  CREATE PROCEDURE dbo.usp_INS_TrackSQLStartups
  AS
  INSERT dbo.SQLStartupLog
  (StartupDateTime)
  VALUES (GETDATE())
  GO
  Next, the sp_procoption stored procedure is used to set this new procedure to execute when
the SQL Server service restarts:
EXEC sp_procoption @ProcName = 'usp_INS_TrackSQLStartups',
@OptionName = 'startup',
@OptionValue = 'true'
Once the service restarts, a new row is inserted into the table. To disable the stored procedure
again, the following command would need to be executed:
EXEC sp_procoption @ProcName = 'usp_INS_TrackSQLStartups',
@OptionName = 'startup',

Encrypting & Recompiling a Store Procedure

June 1st, 2008 Posted in SQL Server, Stored Procedure  No Comments »

Encrypting a store procedure

Just like a view, stored procedure Transact-SQL definitions can have their contents encrypted in the database, removing the ability to read the procedure’s definition. Software producers who use SQL Server in their back-end, often encrypt stored procedures in order to prevent tampering or reverseengineering from clients or competitors. If you use encryption, be sure to save the original definition, as it can’t be decoded later(legally and reliably, anyhow). It should also be encrypted only prior to a push to production. In order to encrypt the stored procedure, WITH ENCRYPTION is designated after the name of the new stored procedure, as this next example demonstrates. Recompiling: do not want execution plan for stored procedure inside memory of SQL Server.

CREATE PROCEDURE usp_EncryptedSP

WITH ENCRYPTION|RECOMPILE

AS
select * fromc category
GO
--Once you’ve created WITH ENCRYPTION, you’ll be unable to view the procedure’s text definition:
-- View the procedure's text
EXEC sp_helptext usp_EncryptedSP
This returns:
The text for object 'usp_EncryptedSP' is encrypted.

Using OUTPUT PARAMETER & SET NOCOUNT ON

May 27th, 2008 Posted in SQL Server, Stored Procedure  No Comments »

Creating parameterized stored procedure

CREATE/ALTER PROCEDURE [dbo].[CategoryGet]
(
@CATEGORYID int
)
AS
BEGIN
    SELECT * FROM CATEGORY
	WHERE CATEGORYID=@CATEGORYID
END
GO

Stored procedure using output parameter

CREATE PROCEDURE OutPutParameter

@intInput int,
@intOutput int OUTPUT
AS
 -- SET NOCOUNT ON added to prevent extra result sets from
 -- interfering with SELECT statements.
	SET NOCOUNT ON;

		set @intOutput = @intInput + 1 

GO

--Call it like this:

declare @intResult int
exec OutPutParameter 3 ,@intResult OUT
select @intResult

Using SET NOCOUNT ON

Stops the message that shows the count of the number of rows affected by a Transact-SQL statement or stored procedure from being returned as part of the result set.When SET NOCOUNT is ON, the count is not returned. When SET NOCOUNT is OFF, the count is returned.

If your stored procedure performs one or more DML operations that cause informational resultsets to be generated, then these will confuse the task. An informational resultset will be familiar to anyone that uses Query Analyser, as you will have seen them as messages in results, for example (1 row(s) affected). These messages are indistinguishable from the SELECT resultset you are really interested in, and since the task reads the first resultset it encounters, an informational resultset can mask your real data. To suppress this behaviour add the SET NOCOUNT ON statement to the top or your stored procedure or script.

What’s New in High Availability

May 23rd, 2008 Posted in High Availability, SQL Server, SQL Server 2005 Features  No Comments »

New features that have direct or indrect effects on increasing high availability for a SQL Server 2005-based implementation

  1. Increased number of nodes in a SQL cluster—You can create a SQL cluster of up
    to eight nodes on Windows 2003 Data Center and up to four nodes on Windows
    2003 Enterprise Edition.
  2. Ability to do unattended cluster setup—Instead of having to use wizards to set up
    SQL clustering, you can use the Unattended Cluster Setup mode. This is very useful
    for fast re-creation or remote creation of SQL clustering configurations.
  3. Full SQL Server 2005 services as cluster managed resources—All SQL Server 2005
    services are cluster aware.
  4. SQL Server 2005 database mirroring—Database mirroring essentially extends the
    old log shipping feature of SQL Server 2000 and creates an automatic failover capability
    to a “hot” standby server. (Chapter 16, “Database Mirroring,” covers database
    mirroring in detail.)
  5. SQL Server 2005 peer-to-peer replication—a new option of data replication that
    uses a publisher-to-publisher model (hence peer-to-peer).
  6. SQL Server 2005 fast recovery—Administrators can reconnect to a recovering database
    after the transaction log has been rolled forward (and before the rollback
    processing has finished).
  7. Online restore—Database administrators can perform a restore operation while the
    database is still online.
  8. Online indexing—The online index option allows concurrent modifications
    (updates, deletes, and inserts) to the underlying table or clustered index data and
    any associated indexes during index creation time.
  9. Database snapshot—SQL Server 2005 allows for the generation and use of a readonly,
    stable view of a database. The database snapshot is created without the
    overhead of creating a complete copy of the database or having completely redundant
    storage.
  10. Data partitioning improvements—Data partitioning has been enhanced with

    native table and index partitioning, which essentially allow you to manage large

    tables and indexes at a lower level of granularity.

  11. Addition of a snapshot isolation level—A new snapshot isolation (SI) level is being
    provided at the database level. With SI, users can access the last committed row,
    using a transactionally consistent view of the database.
  12. Dedicated administrator connection—SQL Server 2005 introduces a dedicated
    administrator connection that administrators can use to access a running server
    even if the server is locked or otherwise unavailable. This capability enables administrators
    to troubleshoot problems on a server by executing diagnostic functions or
    Transact-SQL statements without having to take down the server.

SQL Server Stored Procedure

May 20th, 2008 Posted in SQL Server, Stored Procedure  No Comments »

INTRODUCTION TO STORED PROCEDURES

  1. Reusable code module stored in database
  2. Contain T-SQL that perform operations on data using DML or objects using DDL
  3. Contain logic error handling statements
  4. Can accept parameters-Input parameters, output parameters
  5. Return multiple results
  6. 3 types of stored procedures-user define, extended & system
  7. Recompile if change in schema or in table structure
  8. DROP PROCEDURE { [ schema_name. ] procedure } [ ,...n ] like

    DROP PROCEDURE dbo.usp_GetCategory</p>

Benefits

  1. Fast, pre-complied & stored in databases ( as long as restart sql server )
  2. Reduce network traffic
  3. Enhance security
  4. Modular programming can save time & maintainability
  5. Can be encrypted
  6. Instead, stored procedures are executed as follows: Exec sp_helpdb;

Syntex

CREATE { PROC | PROCEDURE } [schema_name.]procedure_name [ ; number ]
  [ { @parameter [ schema_name.]data_type }
  [ VARYING ] [ = default ] [ OUT | OUTPUT ]
  ] [ ,...n ]
  [ WITH { [ ENCRYPTION ]
  , [ RECOMPILE ]
  , [ EXECUTE_AS_Clause ]
  [ ,...n ] ]
  [ FOR REPLICATION ]
  SQL_Statements
[ RETURN scalar_expression ]

Basic Stored Procedure Example

CREATE/ALTER  PROCEDURE [dbo].[AllContents]
AS
BEGIN
		select * from contents
END
GO

SQL Server Online Restore

April 21st, 2008 Posted in Restore Database, SQL Server  No Comments »

Restoring to a Point In Time
A point-in-time restore can be done using one of the following:

  1. A specific date/time within the transaction log backup
  2. A specific transaction name that was inserted in the log
  3. An LSN

ONLINE RESTORES

Online restores are new to SQL Server 2005. They allow a filegroup, a file, or a specific
page within a file to be restored while the rest of the database is online. The file or filegroup
that is being restored to must be offline during the duration of the online restore.

TIP

You should take a full backup of a database immediately before taking a read-only file
offline. This simplifies the online restore process and eliminates the need to apply a
bunch of transaction log backups prior to the online restore. This applies only to databases
that are in full or bulk-logged recovery.
The following example demonstrates how to take a read-only file offline:

    ALTER DATABASE AdventureWorks
    MODIFY FILE (NAME = ‘AdventureWorks_ReadOnlyData’, OFFLINE)

When the file is offline, you can perform a restore to that file without affecting the rest of
the database. The following example shows an example of an online restore of a readonly
file to the AdventureWorks database:

      RESTORE DATABASE [AdventureWorks]
      FILE = N’AdventureWorks_ReadOnlyData’

      FROM DISK = N’C:\mssql2005\backup\AdventureWorks_ReadOnlyData.bak’
      WITH FILE = 1, NOUNLOAD, STATS = 10, RECOVERY

Backing Up the Tail of Transaction Log

April 14th, 2008 Posted in Uncategorized  No Comments »
  1. In Event of damaged database, take tail of transaction log backup
  2. Tail is only available for databases having full or bulk-logged recovery mode.
  3. While restoring, resture full, differential and all log backup with norecovery and then restore tail transaction log with recovery.

Tail Log Backup

BACKUP LOG [AdventureWorks]
TO DISK = N’C:\mssql2005\backup\log\AdventureWorks_Tail.trn’
WITH NO_TRUNCATE

NO_TRUNCATE prevents the transactions in the log from being removed and allows the transaction log to be backed up, even if the database is inaccessible. This type of backup is possible only if the transaction log file is accessible and was not on the disk that had the failure.