Friday, November 27, 2009

Some useful Interview questions

What is materialized view?We can name it materialized view in different ways like Schema Binding view, Structure binding view and materilizaed view. The main use of the view is it acts as a table like hold the schema. For a example normal view is a select query written by combining multiple tables. If we want to improve the performance there is only a way that we can alter the statements in better way. But if consider materialized view, one can create indexes apart from altering a query for better performance. As you understood indexes will give more performance compares with any other option available in sql server.

What is the diff between inner join and union?Inner join retrieves the matched data from 2 or more tables where as union will retrieve distinct data from 2 or more tables. Join is like horizontal result, Union is like vertical result.

What is the diff between master database and resource database? If resource database was corrupted sql server will work or not? How you can repair that?
Master and Resource both are system dbs in sql server. But master is the primary database which will contain all security structures, objects structures and other user database dependent information where as resource will have copy of the users database system tables which helps at the time of upgradation or degradation. The resource purpose is intended in Sql server 2005 is only for Upgradation or degradation of the versions or service packs. If resource is not available, then also Sql server will not work as some dependent services are working based on resource db structured in Sql Server 2005. Eg : Alert Service, Performance related services.

If i need to give permission per column in table how you can give and tell me process?--
Step 1:
Create table NB_Perm (sl int, name varchar(10))

--STep 2 :
Create role NB_role

--Step 3 :
grant select (sl) on nb_perm to NB_role
deny select(sl) on nb_perm to NB_Role

Make your users member of this role.

What is use of built/administrator in sql server?It is a Windows Group defaultly created with installation of SQL Server. The role defaultly assigned is Sysadmin. If we want this group to be there in Sql server we can keep it and create the users under this group. For creating users refer Administrator Tools – Computer Management - Users and Groups.

What is the diff between having clause and where clause?‘Having’ clause can be used when the query consists aggregate functions like count, avg …..
Eg : Select id,count(id) from table having count(id)>5
‘Where’ clause can be used to filter the data in any statement irrespective of conditions.

How you can know who was last using the query?In earlier versions we can find by implementing the trigger. But in Sql server 2008 new concept auditing is available. With help of this we can find out.

What is the diff between physical file and logical file and which one you refer at the time shrink the file?Logical and Physical both are database files where logical file available inside the database structure and physical file available at the destination drive. Logical and physical both are important at the time of backup, restore or any kind of database operation. As you requested I refer the logical file only at the time of shrinking or restoring the db.

What is covering Index and can you give me one example?Covering index is an index which helps to reduce the index size in a database. Like a index will improve the performance and as a disadvantage it occupies some space in your db. Suppose if you want to create index by using more columns then you can refer convering index as best solution. Addition to decreasing the table space it gives good performance also as running the indexes only it requires on the columns. The suggestions from my side is create all int kind of data columns in index list and varchar kind of column in include list.
Eg : Create (cluster/nonclustered) index IndexName on table (main columns) include (other columns)


What is live lock?A live lock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A live lock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely

Diff between live lock and dead lockDeadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's process.

A live lock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A Live lock also occurs when read transactions monopolize a table or page, forcing a write
transaction to wait indefinitely

Lock escalationLock escalation is the process of escalating a significant number of row level locks to a single table lock. This is trick performed by SQL Server as a way of conserving memory and improving performance. The problem is it works well for smaller systems but can easily throttle performance on larger systems when the activity reaches a certain threshold.

How can rebuild master dbProcess :
1) Shutdown the SQL server and its services.
2) Goto Program Files\Microsoft SQL Server\80\Tools\Binn directory.
3) Open Rebuildm.exe
4) In the Browse for Folder dialog box, select the \Data folder on the SQL Server 2000 compact disc or in the shared network directory from which SQL Server 2000 was installed, and then click OK.
5) Change collation settings if required or leave it default.
6) In the Rebuild Master dialog box, click Rebuild to start the process.
DTS to SSIS migration
We cannot migrate DTS packages from 2000 to 2005 (or) 2008. If it is simple package then we can use it as it is. If it consists vbcode and all it will not convert instead we need to rewritten the package using SSIS. Because SSIS uses .net code.

Types of replication agentsReplication Snapshot Agent:
Replication Log Reader Agent:
Replication Distribution Agent:
Replication Merge Agent:
Replication Queue Reader Agent:

Public/private networkPublic vs. private networks
Computers that are connected to each other create a network. These networks are often configured with "public" Internet Protocol (IP) addresses -- that is, the devices on the network are "visible" to devices outside the network (from the Internet or another network). Networks can also be configured as "private" -- meaning that devices outside the network cannot "see" or communicate directly to them.
Computers on a public network have the advantage (and disadvantage) that they are completely visible to the Internet. As such, they have no boundaries between themselves and the rest of the Internet community. This advantage oftentimes becomes a distinct disadvantage since this visibility can lead to a computer vulnerability exploit -- a.k.a., a "hack" -- if the devices on the public network are not properly secured.

Monday, November 16, 2009

The difference between Master and Resource databases

The difference between Master and Resource database

Mster db is the mother database for all other databases like it consits of other database information, configurations, file locations, security context and etc. whereas Resource db is a database addition to master consists of database schema and stored procedures which requires to run databases in current instance. Resource db mainly introduced for Upgradation or rollback your installations in Sql server 2005.

Some differences:

Master :
1. Master will have data specific to your instance.

2. The database can be found in your sqlserver installation data folder with the name of master.mdf.

3. For any maintenance activity you need to make the db in single user mode.



Resource :
1. Resource will have schema and stored procedures to run your instance.

2. It is introduced in Sql server 2005 for upgradation purpose. In sql server 2000 if you want to upgrade to a new service pack, you would need to run many log scripts that drop and create system scripts. It is too long process and much time consume. In Sql server 2005 if you install service pack or quick fix a copy of resource database will overrite the old database. With help of this resource db you can easily upgrade or rollback your service packs.


3. The database can be found in your sqlserver installation data folder with the name of mssqlsystemresource.mdf.

4. It is a hidden database, you can't findout it in sysdatabases table. By using serverproperty we can view the information about the resource db.

Wednesday, September 16, 2009

Query to findout JOBs information for a period of time

I hope this requirement is very common in DBA work life, as DBA needs to findout how the JOBs are performing currently and for a long time. I too faced the requirement. I have searched most of the pages from google and I couldn't found the solution. Finally I written the following query spending almost 3 hours.

Hopefully it will useful for all SQL Server DBAs.


Syntax :
Select b.Name JobName, a.step_name,a.run_date,run_time,
case when len(a.run_time) = 5 then convert(varchar,left(a.run_time,1)) + ':' + convert(varchar,left(right(a.run_time,4),2)) + ':' + convert(varchar,right (a.run_time,2))
when len(a.run_time) = 4 then '00' + ':'+convert(varchar,left(a.run_time,2)) + ':'+convert(varchar,right(a.run_time,2))
when len(a.run_time) = 3 then '00:0' + convert(varchar,left(a.run_time,1)) + ':'+convert(varchar,right(a.run_time,2))
when len(a.run_time) = 2 then '00:00:' + convert(varchar,left(a.run_time,2))
when len(a.run_time) = 1 then '00:00:0' + convert(varchar,left(a.run_time,1))
else
convert(varchar,left(a.run_time,2)) + ':' + convert(varchar,left(right(a.run_time,4),2)) + ':' + convert(varchar,right (a.run_time,2)) End run_time,
run_duration,
ISNULL(SUBSTRING(CONVERT(varchar(7),run_duration+1000000),2,2) + ':'
+ SUBSTRING(CONVERT(varchar(7),run_duration+1000000),4,2) + ':'
+ SUBSTRING(CONVERT(varchar(7),run_duration+1000000),6,2),'') AS [Duration], a.message
from sysjobs b inner join sysjobhistory a on a.job_id = b.job_id
where b.name like '%Reindex%' AND step_name not like 'Notification'
and step_name not like '%Job Outcome%' order by b.Name


For the above query you can add filter conditions as per your requirements. By getting the result of above query you can have an idea of how the jobs are involved and making the analysis you can increase the performance of the server.

Thursday, September 10, 2009

Query to findout list of Objects count from all databases in SQL Server :

This is very useful query on DBA daily work environment. I have struggled to findout the information before. Finally I developed following query to get the information.

Select 'select ('''+name+''') Database_name,
(Select count(*) from '+name+'.dbo.sysobjects where xtype = ''u'') Table_Count,
(Select count(*) from '+name+'.dbo.sysobjects where xtype = ''v'') View_Count,
(Select count(*) from '+name+'.dbo.sysobjects where xtype in (''fn'', ''tn'')) func_Count,
(Select count(*) from '+name+'.dbo.sysobjects where xtype = ''p'') proc_Count,
(Select count(*) from '+name+'.dbo.sysobjects where xtype = ''tr'') Trig_Count union all'
from sysdatabases where dbid > 4


Instructions :

* you need to take the result script of above query and execute in other window. And you need to remove 'UNION ALL" from end statement.
* dbid > 4 = it will not show for sysdatabases



Result Query :

select ('TEST') Database_name, (Select count(*) from TEST.dbo.sysobjects where xtype = 'u') Table_Count, (Select count(*) from TEST.dbo.sysobjects where xtype = 'v') View_Count, (Select count(*) from TEST.dbo.sysobjects where xtype in ('fn', 'tn')) func_Count, (Select count(*) from TEST.dbo.sysobjects where xtype = 'p') proc_Count, (Select count(*) from TEST.dbo.sysobjects where xtype = 'tr') Trig_Count

Statistics in Synchronization and Asynchronization mode to gain the performance.

In SQL Server we have Statistics to improve the performance on tables. Following are some of the concepts about Statistics in Synchronization/Asynchronization mode to gain the performance from tables.

1. Statistics Asynchronization mode was introduced in SQL Server 2005. In earlier versions only synchronizations mode was available. But the default level is synchronization only.

2. Synchronization /Asynchronization options are at database level, not individual object level. There is single option we can enable or disable this for entire database. We can do this by using alter database statement.
Syntax : ALTER DATABASE dbName SET AUTO_UPDATE_STATISTICS_ASYNC ON
ALTER DATABASE dbName SET AUTO_UPDATE_STATISTICS_ASYNC OFF

3. To checkup this option on existing databases.
Syntax : Select name,is_auto_update_stats_async_on from sys.databases

1 = enabled
0 = disabled

When the setting is off and a statistics update is initiated due to out-of-date statistics in the execution plan, the query must wait until the statistics update is complete before compiling and then returning the result set. When the setting is on, the query does not need to wait as the statistics update are handled by a background process. Mainly it is using to improve the performance on the tables.

So, prior to utilize the statistics aynchronous option at database level, the following process should do at object level.
1. Create statistics on indexed columns. It is suggestable that statistics must create on composite indexed columns.

2. All the created statistics must be updated regularly. When we update the statistics on regular basis, we can gain the performance from tables.

3. This options will work on tables which are having statistics and updating regularly will improve the performance compare to synchronization mode.

Thursday, August 6, 2009

Class 8 - Functions in SQL Server

FUNCTIONS
What is function ?
A function in SQL Server can be defined primary as 2 types. User Defined Functions which is creating by user based on the requirement and System Defined Functions which was already created by Microsoft and provided for ready use.

These can be classified in other ways also :

The Transact-SQL programming language provides three types of functions:
• Rowset functions
Can be used like table references in an SQL statement.
• Aggregate functions
Operate on a collection of values but return a single, summarizing value.
• Scalar functions
Operate on a single value and then return a single value.

Deterministic and Nondeterministic Functions
All functions are deterministic or nondeterministic:
• Deterministic functions always return the same result any time they are called with a specific set of input values.
• Nondeterministic functions may return different results each time they are called with a specific set of input values.


USER DEFINED FUNCTIONS : When we come to User Defined Function again there are 3 types.
1) Scalar Function
2) Table Valued Function
3) Multi Statement Function

Scalar Functions
Scalare functions always returns single resultant value.
Syntax :
CREATE FUNCTION [ owner. ] fn_name ( [ { @parameter [ AS ] data_type }[ ,...n ] ] )
RETURNS data_type
[ AS ]
BEGIN
function_body
RETURN scalar_expression
END
Eg :
create function fn_studage (@id int) returns int
as
begin
declare @studage int
select @studage = datediff(year,dob,getdate()) from students where id = @id
return @studage
end

Inline Table-Valued Functions
Inline Table-Valued Functions return a resultset, as opposed to a single scalar value. A table valued function specifies the TABLE keyword in its RETURN clause. Its basic form is :
Syntax :
CREATE FUNCTION [ owner_name. ] fn_name ( [ { @parameter [ AS ] type } [ ,...n ] ])
RETURNS TABLE
[ AS ]
RETURN [ ( ] select-statement [ ) ]

An Inline Table-Valued Function created by this command:
CREATE FUNCTION datesales (@deadline as datetime)
RETURNS TABLE
AS
RETURN ( SELECT *
FROM sales
WHERE ord_date > @deadline)

and called by this sequence:
USE PUBS
GO
select * from datesales('09/13/1994')
will yield the following table:
stor_id ord_num ord_date qty payterms title_id
6380 6871 09/14/94 5 Net 60 BU1032
7067 D4482 09/14/94 10 Net 60 PS2091
7131 N914008 09/14/94 20 Net 30 PS2091
7131 N914014 09/14/94 25 Net 30 MC3021
8042 423LL922 09/14/94 15 ON invoice MC3021
8042 423LL930 09/14/94 10 ON invoice BU1032

Multi-statement Table-Valued Function
The final type of UDF is the Multi-statement Table-Valued Function. This UDS also returns a resultset, like the Inline variety UDF, but with a much more powerful result. The Multi-statement UFD can actually create a temporary table, specifying the fields, their type and characteristics. Now the scope of that temporary table is limited to the UDF in which it was defined, so when the UDF ends, the temporary table evaporates too. However, this can be a tremendously powerful technique to obtain or manipulate data.

The general form for the Multi-statement Table-Valued Function is:
CREATE FUNCTION [ owner_name. ] fn_name ( [ { @parameter [AS] type } [ ,...n ] ] )
RETURNS @return_variable TABLE < table_type_definition >
[ AS ]
BEGIN
function_body
RETURN
END
The following creates the datesales2 UDF:
CREATE FUNCTION datesales2 (@deadline datetime) RETURNS @table TABLE (stor_id varchar(6) null, ord_num varchar(8) null, ord_date datetime null, qty int, payterms varchar(20), title_id varchar(6))
AS
BEGIN
INSERT @table
SELECT *
FROM sales
WHERE ord_date > @deadline
RETURN
END
When the function is called by this sequence,
USE PUBS
GO
select * from datesales2('09/13/1994')
The following resultset is displayed and available. (It is the same set displayed in the Inline UDF, but created with the temporary table.)
stor_id ord_num ord_date qty payterms title_id
6380 6871 09/14/94 5 Net 60 BU1032
7067 D4482 09/14/94 10 Net 60 PS2091
7131 N914008 09/14/94 20 Net 30 PS2091
7131 N914014 09/14/94 25 Net 30 MC3021
8042 423LL922 09/14/94 15 ON invoice MC3021
8042 423LL930 09/14/94 10 ON invoice BU1032
Now these temporary tables by me combined, joined, with virtually any number created within the Multi-Tabled UDF, giving the user a very powerful tool for calculating and presenting data from the server in a way that truly leverages the effectiveness of writing code in the native language of SQL Server.

SYSTEM DEFINED FUNCTIONS :

FUNCTION EXPLANATION :

Function category Explanation
Configuration Functions : Returns information about the current configuration.
Cursor Functions : Returns information about cursors.
Date and Time Functions : Performs an operation on a date and time input value and returns either a string, numeric, or date and time value.
Mathematical Functions : Performs a calculation based on input values provided as parameters to the function, and returns a numeric value.
Metadata Functions : Returns information about the database and database objects.
Security Functions : Returns information about users and roles.
String Functions : Performs an operation on a string (char or varchar) input value and returns a string or numeric value.
System Functions : Performs operations and returns information about values, objects, and settings in Microsoft® SQL Server™.
System Statistical Functions : Returns statistical information about the system.
Text and Image Functions : Performs an operation on a text or image input values or column, and returns information about the value.


Configuration Functions :
@@REMSERVERReturns the name of the remote Microsoft® SQL Server™ database server as it appears in the login record.
Syntax
@@REMSERVER
Example :
CREATE PROCEDURE check_server
AS
SELECT @@REMSERVER

@@LANGUAGE
@@SERVERNAME

@@SERVICENAME
Example
SELECT @@SERVICENAME
Here is the result set:
------------------------------
MSSQLServer

@@SPID
@@MAX_CONNECTIONS
The actual number of user connections allowed also depends on the version of SQL Server installed and the limitations of your application(s) and hardware.
To reconfigure SQL Server for fewer connections, use sp_configure.
Examples
SELECT @@MAX_CONNECTIONS

@@VERSION

@@NESTLEVEL
Returns the nesting level of the current stored procedure execution (initially 0).

@@DATEFIRST
Returns the current value of the SET DATEFIRST parameter, which indicates the specified first day of each week: 1 for Monday, 2 for Wednesday, and so on through 7 for Sunday.
Syntax
@@DATEFIRST
Examples
SET DATEFIRST 5
SELECT @@DATEFIRST AS '1st Day', DATEPART(dw, GETDATE()) AS 'Today'
Here is the result set. Counting from Friday, today (Saturday) is day 2.
1st Day Today
---------------- --------------
5 2



2. Cursor Functions
@@CURSOR_ROWS
@@CURSOR_STATUS
@@FETCH_STATUS


3. Date and Time Functions
Datepart Abbreviations
Year yy, yyyy
Quarter qq, q
Month mm, m
dayofyear dy, y
Day dd, d
Week wk, ww
Hour hh
minute mi, n
second ss, s
millisecond ms

DATEADD
Eg : SELECT DATEADD(day, 21, pubdate) AS timeframe fROM titles

DATEDIFF
SELECT DATEDIFF(day, pubdate, getdate()) AS no_of_days
FROM titles

DATENAMESELECT DATENAME(month, getdate()) AS 'Month Name' = February

DATEPARTSELECT DATEPART(month, GETDATE()) AS 'Month Number' = 2

DAY SELECT DAY('03/12/1998') AS 'Day Number'

MONTHSELECT MONTH('03/12/1998') AS 'MONTH Number'

YEARSELECT YEAR('03/12/1998') AS 'YEAR Number'

GETDATE()SELECT GETDATE()

4. Mathematical Functions
CEILING Returns the smallest integer greater than, or equal to, the given numeric expression.
Examples
This example shows positive numeric, negative, and zero values with the CEILING function.
SELECT CEILING($123.45), CEILING($-123.45), CEILING($0.0)
GO
Here is the result set:
--------- --------- -------------------------
124.00 -123.00 0.00

FLOORReturns the largest integer less than or equal to the given numeric expression.
Examples
This example shows positive numeric, negative numeric, and currency values with the FLOOR function.
SELECT FLOOR(123.45), FLOOR(-123.45), FLOOR($123.45)
The result is the integer portion of the calculated value in the same data type as numeric_expression.
--------- --------- -----------
123 -124 123.0000

TRIGNOMETRY :
SIN
COS
TAN
COT


5. Metadata Functions
@@PROCIDReturns the stored procedure identifier (ID) of the current procedure
SELECT @@PROCID AS 'ProcID'

OBJECTPROPERTYIF OBJECTPROPERTY ( object_id('authors'),'ISTABLE') = 2
print 'Authors is a table'

DB_IDReturns the database identification (ID) number.

DB_NAMEReturns the database name.
Ex :
SELECT dbid, DB_NAME(dbid) AS DB_NAME
FROM sysdatabases

OBJECT_ID


6. Security Functions
USER
USER_ID
SUSER_NAME : EG :select SUSER_NAME(0X01)
SUSER_SID : EG : SELECT SUSER_SID('sa')


7. String Functions
LTRIMReturns a character expression after removing leading blanks.
select ltrim(' venkat')

RTRIM
Returns a character string after truncating all trailing blanks.

UPPERReturns a character expression with lowercase character data converted to uppercase.
select upper('venkat')

LOWERReturns a character expression with UPPER character data converted to lowercase.

LENReturns the number of characters, rather than the number of bytes, of the given string expression, excluding trailing blanks.

LEFTReturns the part of a character string starting at a specified number of characters from the left.
Ex : left(‘venkat’,3)

RIGHTReturns the part of a character string starting at a specified number of characters from the right.
Ex : Right(‘venkat’,3)

REPLACEReplaces all occurrences of the second given string expression in the first string expression with a third expression.
Examples
This example replaces the string cde in abcdefghi with xxx.
SELECT REPLACE('abcdefghicde','cde','xxx')


8. System Functions
CASE
CAST and CONVERT
Explicitly converts an expression of one data type to another. CAST and CONVERT provide similar functionality.

CAST : SELECT SUBSTRING(title, 1, 30) AS Title, ytd_sales
FROM titles
WHERE CAST(ytd_sales AS char(20)) LIKE '3%'

CONVERT : SELECT SUBSTRING(title, 1, 30) AS Title, ytd_sales
FROM titles
WHERE CONVERT(char(20), ytd_sales) LIKE '3%'

ISNULLCOALESCE
CURRENT_USER
HOST_ID
HOST_NAME

Eg : CREATE TABLE Orders
(OrderID INT PRIMARY KEY,
Workstation NCHAR(30) NOT NULL DEFAULT HOST_NAME())

@@IDENTITY
ISNUMERIC
@@row_count
SCOPE_IDENTITY
SERVERPROPERTY

eg : SELECT SERVERPROPERTY('servername'),
SELECT SERVERPROPERTY('productlevel')

SYSTEM_USER

@@TRANCOUNT

USER_NAME


System Statistical Functions
@@CONNECTIONSReturns the number of connections, or attempted connections, since Microsoft® SQL Server™ was last started.

@@PACK_RECEIVEDReturns the number of input packets read from the network by Microsoft® SQL Server™ since last started.

@@CPU_BUSYReturns the time in milliseconds (based on the resolution of the system timer) that the CPU has spent working since Microsoft® SQL Server™ was last started.

@@PACK_SENTReturns the number of output packets written to the network by Microsoft® SQL Server™ since last started.

@@TOTAL_ERRORSReturns the number of disk read/write errors encountered by Microsoft® SQL Server™ since last started.

9. Text and Image FunctionsPATINDEX
TEXTPTR
TEXTVALID

Class 7 - Views in SQL Server

VIEW IN SQL SERVER 2000
Views are nothing but saved SQL queries. Suppose you have written a query by using multiple SQL statements to view the data. But it may require that watching the data from these tables whenever required. For this you don’t need to write all these queries every time, instead you can save it as a view. View doesn’t contain any data, it is just a query.

CREATE A VIEW
This example creates a view with a simple SELECT statement. A simple view is helpful when a combination of columns is queried frequently.
CREATE VIEW titles_view
AS
SELECT title, type, price, pubdate
FROM titles
GO

JOINS :
Views can be written by using multiple tables with help of joins. There are different joins available in SQL Server. As per the requirement we can choose join to use in the queries for view.

INNER
LEFT OUTER
RIGHT OUTER
FULL
CROSS
SELF
CARTISAN

Eg : Create view ABCD_View
AS
Select a.Col1, a.col2, b.col1, b.col2
from Table_A inner join Table_B
on a.Col1 = b.Col2


Some Arguments about Views in Sql Server 2000 :
You can create views only in the current database. However, the tables and views referenced by the new view can exist in other databases or even other servers if the view is defined using distributed queries.
• A view can reference a maximum of 1,024 columns.
• A View can be used as a security mechanism like we can given permissions for the users also.
• View names must follow the rules for identifiers and must be unique for each user. Additionally, the name must not be the same as any tables owned by that user.
• You can build views on other views and on procedures that reference views. Microsoft® SQL Server™ 2000 allows views to be nested up to 32 levels.
• You cannot associate rules or DEFAULT definitions with views.
• You cannot associate AFTER triggers with views, only INSTEAD OF triggers.
• The query defining the view cannot include the ORDER BY, COMPUTE, or COMPUTE BY clauses or the INTO keyword.
• You cannot define full-text index definitions on views.
• You cannot create temporary views, and you cannot create views on temporary tables.
• Views or tables participating in a view created with the SCHEMABINDING clause cannot be dropped, unless the view is dropped or changed so that it no longer has schema binding. In addition, ALTER TABLE statements on tables that participate in views having schema binding will fail if these statements affect the view definition.
• When a view is created, the name of the view is stored in the sysobjects table.
• If the new table (or view) structure changes, then the view must be dropped and recreated.

View can be createD by using following options for security and performance purposes.

WITH CHECK OPTIONForces all data modification statements executed against the view to adhere to the criteria set within select_statement. When a row is modified through a view, the WITH CHECK OPTION ensures the data remains visible through the view after the modification is committed.
Eg :
CREATE VIEW CAonly
AS
SELECT au_lname, au_fname, city, state
FROM authors
WHERE state = 'CA'
WITH CHECK OPTIONGO

WITH ENCRYPTIONIndicates that SQL Server encrypts the system table columns containing the text of the CREATE VIEW statement. Using WITH ENCRYPTION prevents the view from being published as part of SQL Server replication.
Eg :
CREATE VIEW CAonly
AS
SELECT au_lname, au_fname, city, state
FROM authors
WHERE state = 'CA'
WITH ENCRYPTION
GO

SCHEMABINDINGBinds the view to the schema. When SCHEMABINDING is specified, the select_statement must include the two-part names (owner.object) of tables, views, or user-defined functions referenced.
Views or tables participating in a view created with the schema binding clause cannot be dropped unless that view is dropped or changed so that it no longer has schema binding. Otherwise, SQL Server raises an error. In addition, ALTER TABLE statements on tables that participate in views having schema binding will fail if these statements affect the view definition.

Use built-in functions within a view : This example shows a view definition that includes a built-in function. When you use functions, the derived column must include a column name in the CREATE VIEW statement.
CREATE VIEW categories (category, average_price)
AS
SELECT type, AVG(price)
FROM titles
GROUP BY type
GO

Sunday, July 5, 2009

Class 6 - Knowlege before writing Queries

KNOWLEDGE BEFORE WRITING QUERIES

WILDCARD EXAMPLES :
% - V% - VENKAT, VIJAY, VAMSI
- - V-NKAT - VENKAT
[] - [CS]HERYL - CHERYL, SHERYL
[^] - [^C] - SHERYL

FUNCTIONS :
Arithmetic operators
Comparison operators
Logical operators
Assignment operators
String concatenation operators
Unary operators

Arithmetic Operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo (returns the integer remainder of a division)

Comparison Operators
= Equal to
> Greater than
<>= Greater than or equal to
<= Less than or equal to <> Not equal to
! = Not equal to (SQL-89 standard)
! <> Not greater than (SQL-89 standard)

Logical Operators
AND True if both expressions evaluate to true
BETWEEN True if the value is within a specified range
IN True if the result is equal to one in a list
LIKE True if the result matches a pattern
NOT Reverses the value of any other logical operator (such as NOT IN)
OR True if either logical expression evaluates to true
EXISTS True if a subquery (introduced later in this session) returns any Records

---ALL True if all of a set of compared values evaluates to true
---ANY True if any one of a set of compared values evaluates to true
---SOME True if some of a set of compared values evaluates to true

The assignment operator
Transact-SQL only has one assignment operator, and you’ve probably guessed it
already—it’s the equals sign (=). You use it when assigning values to variables or
specifying column headings.

The string concatenation operator
String concatenation is an operation you’ll find yourself performing over and over
again. Luckily, it is very intuitive—T-SQL uses the plus sign (+) to concatenate
strings. You can use it in SELECT statements like the following:
SELECT au_fname + ‘,’ + au_lname FROM authors

Unary Operators
Operator Description
+ The number is positive
- The number is negative

Working with Aggregate Functions
DISTINCT tells the query to ignore duplicate values, and ALL is a default
SUM returns the total of all the values in a numeric field
AVG returns the average of all the values in the numeric column:
COUNT returns the number of records in the group:
COUNT_BIG for big size purpose
MAX returns the highest value in the column:
MIN returns the lowest value in the column:
STDEV finding standar deviation
STDEVP finding standar deviation

CLAUSES :
AS
SET
ORDER BY
GROUP BY
UNION
UNIONALL
HAVING


CASE FUNCTION :
SELECT case when id = 4 then 'VENKAT' ELSE 'VIJAY' END NAME FROM SYSOBJECTS
WHILE : WHILE (SELECT AVG(price) FROM titles) < $30BEGIN UPDATE titles SET price = price * 2 SELECT MAX(price) FROM titles IF (SELECT MAX(price) FROM titles) > $50 BREAK ELSE CONTINUEENDPRINT 'Too much for the market to bear'
IFDECLARE @msg varchar(255)IF (SELECT COUNT(price) FROM titles WHERE title_id LIKE 'TC%' AND price BETWEEN 10 AND 20) > 0 BEGIN SET NOCOUNT ON SET @msg = 'There are several books that are a good value between $10 and $20. These books are: ' PRINT @msg SELECT title FROM titles WHERE title_id LIKE 'TC%' AND price BETWEEN 10 AND 20 ENDELSE BEGIN SET NOCOUNT ON SET @msg = 'There are no books between $10 and $20. You might consider the following books that are under $10.' PRINT @msg SELECT title FROM titles WHERE title_id LIKE 'TC%' AND price <>Inbuilt functions :
GOTO
WAITFOR
RTRIM (select Right of given characters)
LTRIM (select Right of given characters)
Getdate()
Cast
Convert
Isnull
Coleasce
Datediff
Identity


Queries :
SELECT employeeID, firstname, lastname FROM names WHERE dept = 'prod' or city = 'Orlando' or division = 'food'

UNION ALL
SELECT employeeID, firstname, lastname FROM names WHERE dept = 'prod' UNION ALL SELECT employeeID, firstname, lastname FROM names WHERE city = 'Orlando' UNION ALL SELECT employeeID, firstname, lastname FROM names WHERE division = 'food'


GROUP BY
USE Northwind SELECT OrderID FROM [Order Details] WHERE UnitPrice > 10 GROUP BY OrderID
Using a NOT EXISTS
SELECT a.hdr_key FROM hdr_tbl a WHERE NOT EXISTS (SELECT * FROM dtl_tbl b WHERE a.hdr_key = b.hdr_key)
Using a NOT IN
SELECT hdr_key FROM hdr_tbl WHERE hdr_key NOT IN (SELECT hdr_key FROM dtl_tbl)

QUERY :
SELECT companyid, plantid, formulaid FROM batchrecords WHERE companyid = '0001' and plantid = '0202' and formulaid = '39988773' OR companyid = '0001' and plantid = '0202'


QUERY WITH VARIABLE :
DECLARE @age int SET @age = "30" DECLARE @service_years int SET @service_years = "10" SELECT employee_id FROM employees WHERE age = @age and service_years = @service_years



................. I will post more................ wait and see.................

Class 5 - Normalization

Data Models : We can use following models to design our database.
Entity, Hierarchical, Network

DATA MODELING :

1 – 1 Relationship
1 – many
Many – many


1-1 defining with primary – unique key
Students table (studenntID) - Hostel (StudID)

1- many definign Primary – Foreign Key
Students table (StudentID) - Library (StudID)

Many – Many defining with 3 table
Students table (studID) - Subjects (SubjectID) - Third table ( )



NORMALIZATION :

1NF
Eliminate Repeating Groups - Make a separate table for each set of related attributes, and give each table a primary key.
2NF
Eliminate Redundant Data - If an attribute depends on only part of a multi-valued key, remove it to a separate table.
3NF
Eliminate Columns Not Dependent On Key - If attributes do not contribute to a description of the key, remove them to a separate table.
BCNF
Boyce-Codd Normal Form - If there are non-trivial dependencies between candidate key attributes, separate them out into distinct tables.
4NF
Isolate Independent Multiple Relationships - No table may contain two or more 1:n or n:m relationships that are not directly related.
5NF
Isolate Semantically Related Multiple Relationships - There may be practical constrains on information that justify separating logically related many-to-many relationships.
ONF
Optimal Normal Form - a model limited to only simple (elemental) facts, as expressed in Object Role Model notation.
DKNF
Domain-Key Normal Form - a model free from all modification anomalies.

Class 4 - Constraints

CONSTRAINTS :
Primary Key, Foreign Key,Unique ,Default Key,Check,Null

Primary key
NEW TABLE : create table abc (sl int identity(1,1), name varchar(100), constraint PK_sl Primary key(Sl))

ON EXISTING : ALTER TABLE ABC ADD CONSTRAINT pk_sL PRIMARY KEY (SL)

DROPPING : ALTER TABLE ABC DROP CONSTRAINT pk_sL


Foreign Key
NEW TABLE : CREATE TABLE ABCD (SL INT, PLACE VARCHAR(100),DISTRICT VARCHAR(50), CITY VARCHAR(50), CONSTRAINT FK_sl$abc$sl Foreign Key (Sl) references abc(Sl))

ON EXISTING : alter table abcd ADD constraint FK_Sl$abc$sl FOREIGN KEY (SL) REFERENCES ABC(SL)

DROPPNG : alter table abcd drop constraint FK_Sl$abc$sl


unique
NEW TABLE : create table abcde (sl int, rollnum int, classname varchar(10),
Constraint UQ_rollnum Unique(rollnum))

ON EXISTING : ALTER TABLE ABCDE ADD CONSTRAINT uq_ROLLNUM UNIQUE CLUSTERED (ROLLNUM)

DROPPING : ALTER TABLE ABCDE DROP CONSTRAINT UQ_ROLLNUM


check
NEW TABLE : CREATE TABLE ABCDEF (SL INT, AMOUNT INT, CONSTRAINT ch_AMOUNT CHECK(AMOUNT>5))

ON EXISTING : ALTER TABLE ABCDEF ADD CONSTRAINT CH_AMOUNT CHECK(AMOUNT>5)

DROPPING : ALTER TABLE ABCDEF DROP CONSTRAINT CH_AMOUNT


default
CREATE TABLE ABCDEFF (SL INT, MARKS INT DEFAULT 35)

Null / not null

Class 3 - Brief about T-SQL

Brief about TSQL

DDL – DATA DEFINITION LANGUAGE
DML – DATA MANIPULATION LANGUAGE
DCL – DATA CONTROL LANGUAGE
TCL – TRANSACT CONTROL LANGUAGE

DDL – CREATE, ALTER, DROP, TRUNCATE

Eg : CREATE DATABASE SampleDatabase
ON
( NAME = MyDatabase,
FILENAME = ‘C:\program files\MyData\mydatabasefile.mdf’,
SIZE = 10MB,
MAXSIZE = UNLIMITED,
FILEGROWTH = 1MB)
LOG ON
( NAME = MyDatabase_LOG,
FILENAME = ‘C:\program files\MyData\mydatabaselog.ldf’,
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB )

Eg :
CREATE TABLE MyTable (
Field1 int PRIMARY KEY,
Field2 char(10) NOT NULL),
Field3 datetime
)

Eg : ALTER DATABASE SampleDatabase
ADD FILE
(
NAME = MyDatabase1,
FILENAME =’c:\program files\MyData\mydatabasefile2.ndf’,
SIZE = 10MB,
MAXSIZE = 50MB,
FILEGROWTH = 1MB
)

Eg : ALTER TABLE MyTable ADD Field4 VARCHAR(10) NULL
ALTER TABLE MyTable DROP COLUMN Field4

Eg : DROP DATABASE SampleDatabase

Eg : DROP TABLE MyTable

DML – SELECT, INSERT, UPDATE, DELETE

Eg : _ SELECT @@lNGUAGE displays the name of your SQL Server language.
_ SELECT @@SERVERNAME displays the name of the SQL Server for the current connection.
_ SELECT @@VERSION displays information about Microsoft SQL Server version, build, edition, and so on.
_ SELECT @@TRANCOUNT displays the number of open transactions for the current connection.
_ SELECT @@ERROR displays an error number giving

SELECT :
Select * from [ABCD]

INSERT :
Insert into ABCD [ColumnA, ColumnB] values 5, 6

Insert into ABCD values 5,6

DELETE
Delete from ABCD where ColumnA = 5

UPDATE
Update ABCD set ColumnA = 8 where ColumnA = 5

DCL – GRANT, REVOKE
CREATE LOGIN [venky] WITH PASSWORD=N'111'
CREATE USER [venky] FOR LOGIN [venky]
EXEC sp_addrolemember N'db_owner', N'venky'
DROP LOGIN [venky]

Grant select to venkat
Revoke select to venkat

TCL – COMMIT, ROLLBACK
Commit
Rollback

Class 2 - Data Types

DATA TYPES :
Exact Numerics

bigint
decimal
int
numeric
smallint
money
tinyint
smallmoney
bit

Approximate Numerics
float
real

Date and Time
datetime
smalldatetime

Character Strings
char
text
varchar

Unicode Character Strings
nchar
ntext
nvarchar

Binary Strings
binary
image
varbinary

Other Data Types
cursor
timestamp
sql_variant
uniqueidentifier
table
xml
See Also
New Datatypes :
Varchar(max)
Nvarchar(max)
Varbinary(max)
xml

Exact-number data types that use integer data.
Data type Range Storage

bigint -2^63 (-9,223,372,036,854,775,808) to 2^63-1 (9,223,372,036,854,775,807) 8 Bytes
int -2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647) 4 Bytes
smallint -2^15 (-32,768) to 2^15-1 (32,767) 2 Bytes
tinyint 0 to 255 1 Byte

decimal and numeric (Transact-SQL)
Numeric data types that have fixed precision and scale.
decimal[ (p[ , s] )] and numeric[ (p[ , s] )]
Fixed precision and scale numbers. When maximum precision is used, valid values are from - 10^38 +1 through 10^38 - 1. The SQL-92 synonyms for decimal are dec and dec(p, s). numeric is functionally equivalent to decimal.
p (precision)
The maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. The precision must be a value from 1 through the maximum precision of 38. The default precision is 18.
s (scale)
The maximum number of decimal digits that can be stored to the right of the decimal point. Scale must be a value from 0 through p. Scale can be specified only if precision is specified. The default scale is 0; therefore, 0 <= s <= p. Maximum storage sizes vary, based on the precision. Precision Storage bytes 1 – 9 5 10-19 9 20-28 13 29-38 17 money and smallmoney (Transact-SQL) Data types that represent monetary or currency values. Data type Range Storage money -922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytes smallmoney - 214,748.3648 to 214,748.3647 4 bytes bit (Transact-SQL) An integer data type that can take a value of 1, 0, or NULL. float and real (Transact-SQL) Approximate-number data types for use with floating point numeric data. Floating point data is approximate; therefore, not all values in the data type range can be represented exactly. Note: The SQL-92 synonym for real is float(24). Data type Range Storage float - 1.79E+308 to -2.23E-308, 0 and 2.23E-308 to 1.79E+308 Depends on the value of n real - 3.40E + 38 to -1.18E - 38, 0 and 1.18E - 38 to 3.40E + 38 4 Bytes Date and Time (Transact-SQL) Are data types that are used for representing the date and the time of day. datetime and smalldatetime Represent the date and the time of day. Data type Range Accuracy datetime January 1, 1753, through December 31, 9999 3.33 milliseconds smalldatetime January 1, 1900, through June 6, 2079 1 minute char and varchar (Transact-SQL) Are character data types of either fixed length or variable length. char [ ( n ) ] Fixed-length, non-Unicode character data with a length of n bytes. n must be a value from 1 through 8,000. The storage size is n bytes. The SQL-2003 synonym for char is character. varchar [ ( n max ) ] Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The SQL-2003 synonyms for varchar are char varying or character varying. nchar and nvarchar (Transact-SQL) Character data types that are either fixed-length, nchar, or variable-length, nvarchar, Unicode data and use the UNICODE UCS-2 character set. nchar [ ( n ) ] Fixed-length Unicode character data of n characters. n must be a value from 1 through 4,000. The storage size is two times n bytes. The SQL-2003 synonyms for nchar are national char and national character. nvarchar [ ( n max ) ] Variable-length Unicode character data. n can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size, in bytes, is two times the number of characters entered + 2 bytes. The data entered can be 0 characters in length. The SQL-2003 synonyms for nvarchar are national char varying and national character varying. ntext, text, and image (Transact-SQL) Important: ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead. For more information, see Using Large-Value Data Types.
Fixed and variable-length data types for storing large non-Unicode and Unicode character and binary data. Unicode data uses the UNICODE UCS-2 character set.

ntext
Variable-length Unicode data with a maximum length of 2^30 - 1 (1,073,741,823) characters. Storage size, in bytes, is two times the number of characters entered. The SQL-2003 synonym for ntext is national text.

text
Variable-length non-Unicode data in the code page of the server and with a maximum length of 2^31-1 (2,147,483,647) characters. When the server code page uses double-byte characters, the storage is still 2,147,483,647 bytes. Depending on the character string, the storage size may be less than 2,147,483,647 bytes.

image
Variable-length binary data from 0 through 2^31-1 (2,147,483,647) bytes.

binary and varbinary (Transact-SQL)
Binary data types of either fixed length or variable length.
binary [ ( n ) ]
Fixed-length binary data with a length of n bytes, where n is a value from 1 through 8,000. The storage size is n bytes.

varbinary [ ( n max) ]
Variable-length binary data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of the data entered + 2 bytes. The data that is entered can be 0 bytes in length. The SQL-2003 synonym for varbinary is binary varying.

cursor (Transact-SQL)
A data type for variables or stored procedure OUTPUT parameters that contain a reference to a cursor. Any variables created with the cursor data type are nullable.
The operations that can reference variables and parameters having a cursor data type are:
The DECLARE @local_variable and SET @local_variable statements.
The OPEN, FETCH, CLOSE, and DEALLOCATE cursor statements.
Stored procedure output parameters.
The CURSOR_STATUS function.
The sp_cursor_list, sp_describe_cursor, sp_describe_cursor_tables, and sp_describe_cursor_columns system stored procedures.

Sql_variant (Transact-SQL)
A data type that stores values of various SQL Server 2005-supported data types, except text, ntext, image, timestamp, and sql_variant.
uniqueidentifier (Transact-SQL)
Is a 16-byte GUID.
Remarks
A column or local variable of uniqueidentifier data type can be initialized to a value in the following ways:
By using the NEWID function.
By converting from a string constant in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, in which each x is a hexadecimal digit in the range 0-9 or a-f. For example, 6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid uniqueidentifier value.

xml (Transact-SQL)
Updated: 5 December 2005
Is the data type that stores XML data. You can store xml instances in a column, or a variable of xml type. For more information, see xml Data Type.
Select * from systypes

Class 1 - Introduction of SQL Server

Overview of Database Concepts

A database is a structured collection of records of data. Its group os objects.
The first database management systems were developed in the 1960s. A pioneer in the field was Charles Bachman
First it was in the form of Files.
Later created like Foxpro, Dbase.
The relational model was proposed by E. F. Codd in 1970.
The rules
Rule 0: The system must qualify as relational, as a database, and as a management system.
For a system to qualify as a relational database management system (RDBMS), that system must use its relational facilities (exclusively) to manage the database.
Rule 1: The information rule:
All information in the database is to be represented in one and only one way, namely by values in column positions within rows of tables.
Rule 2: The guaranteed access rule:
All data must be accessible with no ambiguity. This rule is essentially a restatement of the fundamental requirement for primary keys. It says that every individual scalar value in the database must be logically addressable by specifying the name of the containing table, the name of the containing column and the primary key value of the containing row.
Rule 3: Systematic treatment of null values:
The DBMS must allow each field to remain null (or empty). Specifically, it must support a representation of "missing information and inapplicable information" that is systematic, distinct from all regular values (for example, "distinct from zero or any other number," in the case of numeric values), and independent of data type. It is also implied that such representations must be manipulated by the DBMS in a systematic way.
Rule 4: Active online catalog based on the relational model:
The system must support an online, inline, relational catalog that is accessible to authorized users by means of their regular query language. That is, users must be able to access the database's structure (catalog) using the same query language that they use to access the database's data.
Rule 5: The comprehensive data sublanguage rule:
The system must support at least one relational language that
(a) Has a linear syntax
(b) Can be used both interactively and within application programs,
(c) Supports data definition operations (including view definitions), data manipulation operations (update as well as retrieval), security and integrity constraints, and transaction management operations (begin, commit, and rollback).
Rule 6: The view updating rule:
All views that are theoretically updatable must be updatable by the system.
Rule 7: High-level insert, update, and delete:
The system must support set-at-a-time insert, update, and delete operators. This means that data can be retrieved from a relational database in sets constructed of data from multiple rows and/or multiple tables. This rule states that insert, update, and delete operations should be supported for any retrievable set rather than just for a single row in a single table.
Rule 8: Physical data independence:
Changes to the physical level (how the data is stored, whether in arrays or linked lists etc.) must not require a change to an application based on the structure.
Rule 9: Logical data independence:
Changes to the logical level (tables, columns, rows, and so on) must not require a change to an application based on the structure. Logical data independence is more difficult to achieve than physical data independence.
Rule 10: Integrity independence:
Integrity constraints must be specified separately from application programs and stored in the catalog. It must be possible to change such constraints as and when appropriate without unnecessarily affecting existing applications.
Rule 11: Distribution independence:
The distribution of portions of the database to various locations should be invisible to users of the database. Existing applications should continue to operate successfully :
(a) when a distributed version of the DBMS is first introduced; and
(b) when existing distributed data are redistributed around the system.
Rule 12: The nonsubversion rule:
If the system provides a low-level (record-at-a-time) interface, then that interface cannot be used to subvert the system, for example, bypassing a relational security or integrity constraint.

During the 1980s, research activity focused on distributed database systems and database machines.

In the 1990s, attention shifted to object-oriented databases. These had some success in fields where it was necessary to handle more complex data than relational systems could easily cope with, such as spatial databases, engineering data (including software repositories), and multimedia data.

In the 2000s, the fashionable area for innovation is the XML database. As with object databases, this has spawned a new collection of start-up companies, but at the same time the key ideas are being integrated into the established relational products.

Some of DBMS Products :
ADABAS
BerkeleyDB
dBase
IBM DB2
Informix
Microsoft Access
Microsoft SQL Server
MySQL
Oracle Database
Paradox (database)
Sybase
Teradata

MS SQL SERVER

Microsoft SQL Server is a relational database management system (RDBMS) produced by Microsoft. Its primary query language is Transact-SQL, an implementation of the ANSI/ISO standard Structured Query Language (SQL) used by both Microsoft and Sybase.
For each databse query languge will use :
Oracle : PL/SQL
Sqlserver : T-Sql


Architecture
The architecture of Microsoft SQL Server is broadly divided into three components: SQLOS which implements the basic services required by SQL Server, including thread scheduling, memory management and I/O management; the Relational Engine, which implements the relational database components including support for databases, tables, queries and stored procedures as well as implementing the type system; and the Protocol Layer which exposes the SQL Server functionality.[1]



SQLOS
SQLOS is the base component in the SQL Server architecture. It implements functions normally associated with the Operating System - thread scheduling, memory management, I/O management, buffer pool management, resource management, synchronization primitives and locking, and deadlock detection.

Relational engine
The Relational engine implements the relational data store using the capabilities provided by SQLOS, which is exposed to this layer via the private SQLOS API.


Protocol layer
Protocol layer implements the external interface to SQL Server.



SQL Server 2005
SQL Server 2005, released in November 2005, is the successor to SQL Server 2000. It included native support for managing XML data, in addition to relational data.

SQL Server 2008
The next version of SQL Server is SQL Server 2008,[29] code-named "Katmai",[30] slated to launch on February 27, 2008 and release (RTM) in Q3 2008.[31][32] The most recent CTP was made available on February 19, 2008. SQL Server 2008 aims[33] to make data management self-tuning, self organizing, and self maintaining with the development of SQL Server Always On technologies, to provide near-zero downtime. SQL Server 2008 will also include support for structured and semi-structured data, including digital media formats for pictures, audio, video and other multimedia data. In current versions, such multimedia data can be stored as BLOBs (binary large objects), but they are generic bitstreams. Intrinsic awareness of multimedia data will allow specialized functions to be performed on them. According to Paul Flessner, senior Vice President, Server Applications, Microsoft Corp., SQL Server 2008 can be a data storage backend for different varieties of data: XML, email, time/calendar, file, document, spatial, etc as well as perform search, query, analysis, sharing, and synchronization across all data types.[30]


Tools
SQLCMD
SQLCMD is a command line application that comes with Microsoft SQL Server, and exposes the management features of SQL Server. It allows SQL queries to be written and executed from the command prompt.

Visual Studio
Microsoft Visual Studio includes native support for data programming with Microsoft SQL Server. It can be used to write and debug code to be executed by SQL CLR.
SQL Server Management Studio is a GUI tool included with SQL Server 2005 and later for configuring, managing, and administering all components within Microsoft SQL Server.
Business Intelligence Development Studio
Business Intelligence Development Studio (BIDS) is the IDE from Microsoft used for developing data analysis and Business Intelligence solutions utilizing the Microsoft SQL Server Analysis Services, Reporting Services and Integration Services.

SQL Server Release HistoryVersion Year Release Name Codename

1.0 1989 SQL Server 1.0 -

4.21 1993 SQL Server

6.0 1995 SQL Server

6.5 1996 SQL Server 6.5 Hydra

7.0 1998 SQL Server 7.0 Sphinx-

1999 SQL Server 7.0
OLAP Tools
8.0 2000 SQL Server 2000 Shiloh

8.0 2003 SQL Server 2000 64-bit Edition Liberty

9.0 2005 SQL Server 2005 Yukon

10.0 2008 SQL Server 2008 Katmai

SQL SERVER CLASS

Hi All,

I have prepared this class material for the learners who are new to SQL Server. By studying this you can gain knowledge in SQL Server. Actually I have take SQL Server 2000 for preparing this class materials, because I felt like it would be better first learn the older versions then come to newer. Hope it will helpful for everyone who are new to SQL Server.

Follow my lession in the Blog :

Thursday, July 2, 2009

SQL SERVER 2008 NEW DATA TYPES

NEW DATA TYPES in SQL Server 2008

• Date and Time: Four new date and time data types have been added, making working with time much easier than it ever has in the past. They include: DATE, TIME, DATETIME2, and DATETIMEOFFSET.
• Spatial: Two new spatial data types have been added GEOMETRY and GEOGRAPHY which you can use to natively store and manipulate location-based information, such as Global Positioning System (GPS) data.
• HIERARCHYID: The HIERARCHYID data type is used to enable database applications to model hierarchical tree structures, such as the organization chart of a business.
• FILESTREAM: FILESTREAM is not a data type as such, but is a variation of the
VARBINARY(MAX) data type that allows unstructured data to be stored in the file system
instead of inside the SQL Server database. Because this option requires a lot of involvement
from both the DBA administration and development side.

…. Working on each data type practical, I will post with examples once I finished.

Wednesday, July 1, 2009

FIND LIST OF JOBS AND ITS DETAILS IN SQL SERVER


-- JOBWISE INFORMATION
select distinct a.name JOBNAME, isnull(DESCRIPTION,'No description available') DESCRIPTION,c.Name Category, isnull (b.database_name,'None') DATABASE_NAME, isnull(f.name, 'None') Job_Owner,
case when d.name is null then 'No Schedule' else d.name end Schedule,
isnull (case d.freq_type
when '1 ' then 'Once'
when '4' then 'Daily'
when '8' then 'Weekly'
when '16' then 'Monthly'
when '32' then 'Monthly relative'
when '64' then 'When SQL Server Agent starts' end, 'None') as Frequency,
isnull (case d.freq_interval
when '1' then 'None'
when '2' then 'Monday'
when '4' then 'Tuesday'
when '8' then 'Wednesday'
when '16' then 'Thursday'
when '32' then 'Friday'
when '64' then 'Saturday'
end,'None') as DAY,
case when active_start_time < 120000 then
isnull(left(convert(varchar,convert(decimal,D.Active_start_time)/10000),4) + ' AM','None') else
isnull(left(convert(varchar,convert(decimal,D.Active_start_time)/10000-12),4) + ' PM','None') END
JOB_start_time,
isnull (convert (varchar,d.Date_Created), 'None') Created_Date from sysjobs a
Inner join sysjobsteps b on
a.job_id = b.job_id
left outer join syscategories c on a.category_id = c.category_id
left outer join master.dbo.syslogins f on a.Owner_sid = f.sid
left outer join sysjobschedules e on e.job_id = a.job_id
left outer join sysschedules d on e.schedule_id = d.schedule_id
order by a.name



--JOB STEP WISE INFORMATION
select distinct a.name JOBNAME, isnull(DESCRIPTION,'No description available') DESCRIPTION,c.Name Category, isnull (b.database_name,'None') DATABASE_NAME, isnull(f.name,'None') Job_Owner,
b.step_id STEP, b.step_name STEPNAME,b.subsystem TYPE,b.command,
case when d.name is null then 'No Schedule' else d.name end Schedule,
isnull (case d.freq_type
when '1 ' then 'Once'
when '4' then 'Daily'
when '8' then 'Weekly'
when '16' then 'Monthly'
when '32' then 'Monthly relative'
when '64' then 'When SQL Server Agent starts' end, 'None') as Frequency,
isnull (case d.freq_interval
when '1' then 'None'
when '2' then 'Monday'
when '4' then 'Tuesday'
when '8' then 'Wednesday'
when '16' then 'Thursday'
when '32' then 'Friday'
when '64' then 'Saturday'
end,'None') as DAY,
case when active_start_time < 120000 then
isnull(left(convert(varchar,convert(decimal,D.Active_start_time)/10000),4) + ' AM','None') else
isnull(left(convert(varchar,convert(decimal,D.Active_start_time)/10000-12),4) + ' PM','None') END
JOB_start_time,
isnull (convert (varchar,d.Date_Created), 'None') Created_Date from sysjobs a
left outer join sysjobsteps b on
a.job_id = b.job_id
left outer join syscategories c on a.category_id = c.category_id
left outer join master.dbo.syslogins f on a.Owner_sid = f.sid
left outer join sysjobschedules e on e.job_id = a.job_id
left outer join sysschedules d on e.schedule_id = d.schedule_id
order by a.name

Tuesday, April 28, 2009

MOVING TEMPDB

MOVING TEMPDB FROM DEFAULT LOCATION TO REQUIRED PATH :

When installa SQL Server all system databases will be intsalled at Progra Files - Microsoft SQL Server - Data folder. But it is suggestable that move Tempdb databsae into another driver for better performance. Moving tempdb is not like normal process, Attach/Detach, Backup/Restore, it can be done in following way.

How to move tempdb

1) Find the tempdb database file details.

sp_helpdb tempdb

2)
ALTER DATABASE tempdb
MODIFY FILE (NAME = tempdev, FILENAME = 'C:\tempdb\tempdb2005.mdf')
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = templog, FILENAME = 'C:\tempdb\tempdb2005.ldf')

* C:\tempdb is the new location where we want to move the tempdb files.

Tuesday, March 31, 2009

How to findout list of users and thier permissions in a Database

I have struggled almost a week to findout the solution. From google also I found different suggestions in various sites, but it doesn't met to my requirement. Finally I got up the solution.

1) SELECT UID, NAME, HASDBACCESS,B.* FROM SYSUSERS A INNER JOIN SYSPERMISSIONS B ON A.UID = B.ID

2) Exec sp_helprotect null,'UserName'

for assigning role to login we can use sys procedures like
sp_addrolemember, sp_change_users_login ........

Tuesday, March 24, 2009

Mirror the Database using SQL Server 2005

Mirroing is the new concept introduced in SQL Server 2005. It is very useful to maintain a standby database when disaster occurs. Following is the process how to configure mirroring and test.

1) Create & backup database test_mirror to disk='d:\test_mirror.bkp'

2) backup log test_mirror to disk='d:\test_mirror_log.bkp'

3) move the backup file into destination server

4) Restore the database with norecovery

RESTORE DATABASE [test_mirror] FROM DISK = N'd:\test_mirror.bkp' WITH FILE = 1,

NORECOVERY, NOUNLOAD, REPLACE, STATS = 10
GO

5) Restore the log with norecovery

RESTORE log [test_mirror] FROM DISK = N'd:\test_mirror_log.bkp' WITH FILE = 1,

NORECOVERY, NOUNLOAD, REPLACE, STATS = 10

6) Configure the mirroring

a) Select test_mirror database right click - go to tasks - select mirror
b) Configure the Security using configure Security button. It will prompt for the

connections and authentication. You can configure different servers or 2 instances for

mirroring.
c) As first step it will ask for Witness server, this is optional. Witness server

can be configured to watch the mirroring from different server.
d) Principal and Mirror servers can be configured using next steps.
e) Select Operating Mode either Asynchronous(high performance) or Synchronous (high protection).
Asynchronous is nothing but changes will happend at principal server first then changes pass to mirror server.
Synchronous is like changes will happend same time at both the servers.


7) create the test table before start the mirroring.

create table test_1(regno numeric)


8) Start the mirroring

9) create the test_2 table after start the mirroring

create table test_2(regno numeric)

10) Create the snapshot copy in destination

CREATE DATABASE test_mirror_copy ON
(
NAME = test_mirror,
FILENAME = 'd:\testmirror.ss'
)
AS SNAPSHOT OF test_mirror

11) In the snapshot copy I can see both test-1 and test_2 tables.


12) Insert data into test_1 table

insert into test_1 values(1)

13) drop the existing snapshot

EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'test_mirror_copy'
GO
USE [master]
GO
/****** Object: Database [test_mirror_copy] Script Date: 03/18/2009 05:38:05 ******/
DROP DATABASE [test_mirror_copy]
GO


14) create the new snapshot

CREATE DATABASE test_mirror_copy ON
(
NAME = test_mirror,
FILENAME = 'd:\testmirror.ss'
)
AS SNAPSHOT OF test_mirror

15) So we can able to see one row in test_1 table. It means mirror happening from

principle to mirror server.






Note :
** If you are using SQL server 2005 with Service Pack 2, then no need to configure any trace flags. Otherwise Trace Flag 1400 is required to put in start up Parameters.

- Open Configuration Tools
- Goto Sql Server Configuration Manager
- Goto SQL Server 2005 Services
- then open the sql server service
- goto Advanced
- in startup parameters mention ;-T1400 (T should be capital)
- restart the service to effect the settings

Tuesday, March 17, 2009

SQL Server 2005 New Features for improving Performance

TABLE OF CONTENTS

1. SCHEMA BINDING VIEW (Materialized View) :
2. CTE (Common Table Expression) :
3. TABLE PARTITION :
4. OUTPUT Keyword :
5. PIVOT / UNPIVOT :
6. APPLY Operator :
7. RANKING FUNCTIONS :
8. SQL SERVER 2005 INDEX FEATURES :
9. Sp_Executesql



1. SCHEMA BINDING VIEW (Materialized View) :

Schema Binding View is nothing but a view but it will bind the schema like a table. It means the view will hold the data. So we can able to create indexes on that. When index is created on a table automatically it improves the performance.

Benefits of Using Indexed Views :

• It is possible to create a unique clustered index on a view, as well as nonclustered indexes, to improve data access performance on the most complex queries.
• Aggregations can be precomputed and stored in the index to minimize expensive computations during query execution.
• Tables can be prejoined and the resulting data set stored.
• Combinations of joins or aggregations can be stored.

Considerations : The following considerations should follow while creating SB views ..
• The view, and all tables referenced in the view, must be in the same database and have the same owner.
• The indexed view does not need to contain all the tables referenced in the query to be used by the optimizer.
• A unique clustered index must be created before any other indexes can be created on the view.
• The view must be created using schema binding and any user-defined functions referenced in the view must also be created with the SCHEMABINDING option.
• Additional disk space will be required to hold the data defined by the indexed view.
• DTA (Database Tuning Advisor) tool can be used to findout indexed view requirement. It is a new tool available in SQL 2005 only.

Creating Indexed Views:

The steps required to create an indexed view are critical to the successful implementation of the view.
1. Verify the setting of ANSI_NULLS is correct for all existing tables that will be referenced in the view.
2. Verify ANSI_NULLS is set correctly for the current session as shown in the table below before creating any new tables.
3. Verify ANSI_NULLS and QUOTED_IDENTIFIER are set correctly for the current session as shown in the table below before creating the view.
4. Verify the view definition is deterministic.
5. Create the view using the WITH SCHEMABINDING option.
6. Verify your session's SET options are set correctly as shown in the table below before creating the unique clustered index on the view.
7. Create the unique clustered index on the view.
8. The OBJECTPROPERTY function can be used to check the value of ANSI_NULLS and QUOTED_IDENTIFIER on an existing table or view.

Note The indexed view may contain float and real columns; however, such columns cannot be included in the clustered index key if they are non-persisted computed columns.
GROUP BY Restrictions
If GROUP BY is present, the VIEW definition:
• Must contain COUNT_BIG(*).
• Must not contain HAVING, CUBE, ROLLUP, or GROUPING()
These restrictions are applicable only to the indexed view definition. A query can use an indexed view in its execution plan even if it does not satisfy these GROUP BY restrictions


Example :

CREATE VIEW Vdiscount1 WITH SCHEMABINDING AS
SELECT SUM(UnitPrice*OrderQty) AS SumPrice,
SUM(UnitPrice*OrderQty*(1.00-UnitPriceDiscount)) AS SumDiscountPrice,
COUNT_BIG(*) AS Count, ProductID
FROM Sales.SalesOrderDetail
GROUP BY ProductID

GO

CREATE UNIQUE CLUSTERED INDEX VDiscountInd ON Vdiscount1 (ProductID)

Go

Can create many non clustered indexes

2. CTE (Common Table Expression) :
A named temporary result set based on a SELECT query. By mentioning WITH CTE Name we can write the query and the result set can be used again in the same query. The main purpose of CTE is we can avoid temporary table.

Advantages :
• Result set can be used in SELECT, INSERT, UPDATE, or DELETE
• Queries with derived tables become more readable
• Provide traversal of recursive hierarchies

Example :

WITH TopSales (SalesPersonID, NumSales) AS
(SELECT SalesPersonID, Count(*)
FROM Sales.SalesOrderHeader GROUP BY SalesPersonId)

SELECT LoginID, NumSales
FROM HumanResources.Employee e INNER JOIN TopSales
ON TopSales.SalesPersonID = e.EmployeeID
ORDER BY NumSales DESC



3. TABLE PARTITION :
Partition Tables
Vertical Table Partitioning :
You can use vertical table partitioning to move infrequently used columns into another table. Moving the infrequently used columns makes the main table narrower and allows more rows to fit on a page.

Horizontal Table Partitioning :
Horizontal table partitioning is a bit more complicated. But when tables that use horizontal table partitioning are designed correctly, you may obtain huge scalability gains. One of the most common scenarios for horizontal table partitioning is to support history or archive databases where partitions can be easily delineated by date. A simple method that you can use to view the data is to use partitioned views in conjunction with check constraints.

How to partition a table using Horizontal Partitioning :
Step 1: Create the partition function
CREATE PARTITION FUNCTION emailPF (nvarchar(30))
AS RANGE RIGHT FOR VALUES ('G', 'N')

Step 2: Create the partition scheme
CREATE PARTITION SCHEME emailPS
AS PARTITION emailPF TO (fg1, fg2, fg3)

Step 3 : Create the partitioned table
CREATE TABLE Sales.CustomerEmail
(CustID int, email nvarchar(30))
ON EMailPS (email)

* fg1,fg2,fg3 are filegroups located in different drives.



4. OUTPUT Keyword :

With help of Output keyword we can avoid multiple declarations and assigning the values. While performing INSERT/Update we can take the value into variable and it can be used in further queries.

Example :

DECLARE @InsertDetails TABLE
(ProductModelID int,
InsertedBy sysname)

INSERT INTO Production.ProductModel(Name, ModifiedDate)
OUTPUT inserted.ProductModel ID, suser_name()
INTO @InsertDetails
VALUES
('Racing Bike', getdate())


SELECT * FROM @InsertDetails


5. PIVOT / UNPIVOT :

PIVOT – converts values to columns :

Cust Prod Qty
Mike Bike 3
Mike Chain 2
Mike Bike 5
Lisa Bike 3
Lisa Chain 3
Lisa Chain 4

SELECT * FROM Sales.Order
PIVOT (SUM(Qty) FOR Prod IN ([Bike],[Chain])) PVT

Cust Bike Chain
Mike 8 2
Lisa 3 7


UNPIVOT – converts columns to values :

Cust Bike Chain
Mike 8 2
Lisa 3 7

SELECT Cust, Prod, Qty
FROM Sales.PivotedOrder
UNPIVOT (Qty FOR Prod IN ([Bike],[Chain])) UnPVT

Cust Prod Qty
Mike Bike 8
Mike Chain 2
Lisa Bike 3
Lisa Chain 7


6. APPLY Operator :

With help of APPLY operator we can join a function with table and get the result. In SQL 2000 then function result need to be inserted in a table, then only we can make a join from that. But using APPLY operator directly joining with table we can get the output.

Advantages : Invokes a table-valued function once per row
 CROSS APPLY – only rows with matching function results
 OUTER APPLY – all rows, regardless of matching function results


Example :

CREATE FUNCTION Sales.MostRecentOrders
(@CustID AS int) RETURNS TABLE AS
RETURN
SELECT TOP(3) SalesOrderID, OrderDate
FROM Sales.SalesOrderHeader
WHERE CustomerID = @CustID
ORDER BY OrderDate DESC


SELECT Name AS Customer, MR.*
FROM Sales.Store
CROSS APPLY Sales.MostRecentOrders(CustomerID) AS MR

7. RANKING FUNCTIONS :

Function Description
RANK Returns a rank for each row within a specified partition in a result set
DENSE_RANK Returns a consecutive rank for each row within a specified partition in a result set
ROW_NUMBER Returns the ordinal row position of each row in a grouping within a result set
NTILE Divides the rows in each partition of a result set into a specified number of ranks based on a given value.

With help of ranking functions we can find the data sequentially, like we can avoid top and other keywords.
8. SQL SERVER 2005 INDEX FEATURES :

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 data definition language (DDL) execution. For example, while a clustered index is being rebuilt, you can continue to make updates to the underlying data and perform queries against the data.
Eg :
CREATE CLUSTERED INDEX [PK_Employee_EmployeeID] ON [HumanResources].[Employee] ([EmployeeID] ASC)
WITH (PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = ON) ON [PRIMARY]

ALTER INDEX ALL on HumanResources.Employee REBUILD WITH (ONLINE=ON)

INCLUDE CLAUSE :
With help of include clause, by including non-key columns we can create non-clustered indexes that cover more queries. The Database Engine does not consider non-key columns when calculating the number of index key columns or index key size. Non-key columns can be included in non-clustered index to avoid exceeding the current index size limitations of a maximum of 16 key columns and a maximum index key size of 900 bytes. INCLUDE clause to CREATE INDEX for nonkey columns – stored in leaf nodes of the index

Eg :

create unique index XUpersonInterest_firstName_inclInterest
on personInterest(firstName) include (interest)

CREATE NONCLUSTERED INDEX IX_Address_PostalCode
ON Person.Address (PostalCode)
INCLUDE (AddressLine1, AddressLine2, City, StateProvinceID)


ALTER INDEX :
Disabling
ALTER INDEX IX_Customer_TerritoryID ON Sales.Customer DISABLE

Rebuilding
ALTER INDEX PK_Customer_CustomerID ON Sales.Customer REBUILD

Reorganizing
ALTER INDEX PK_Customer_CustomerID ON Sales.Customer REORGANIZE

Setting of options
ALTER INDEX PK_Customer_CustomerId ON Sales.Customer SET(...)



Index related considerations for improving performance :
• Create indexes based on use :
Do not create indexes if a table is rarely queried, or if a table does not ever seem to be used by the optimizer. Avoid indexes on bit, text, ntext, or image data types because they are rarely used. Avoid very wide indexes and indexes that are not selective.
• Keep clustered index keys as small as possible.
• Consider range data for clustered indexes.
• Create an index on all foreign keys.
• Create highly selective indexes.
Create indexes that exhibit high selectivity. In other words, create indexes that have many distinct values. For example, an index on a region column may have a small number of distinct values. Therefore, there may not be enough distinct values for the optimizer to use. Another example of an item that may not have enough distinct values is a bit column. Since there are only two values, an index cannot be very selective and as a result, the index may not be used.
• Consider a covering index for often-used, high-impact queries.
• Use multiple narrow indexes rather than a few wide indexes.
• Create composite indexes with the most restrictive column first.
• Consider indexes on columns used in WHERE, ORDER BY, GROUP BY, and DISTINCT clauses.
• Remove unused indexes.
• Use the Index Tuning Wizard to tune the indexes.
• Keep statistics up to date

9. sp_executesql :

This system procedure can be used to execute dynamic sql queries instead of using EXEC keyword. Compare with EXEC keyword it will give the much performance.

Example :

DECLARE @SQLString NVARCHAR(500);

--Set column list. CHAR(13) is a carriage return, line feed
SET @SQLString = N'SELECT FirstName, LastName, JobTitle' + CHAR(13);

-- Set FROM clause with carriage return, line feed.
SET @SQLString = @SQLString + N'FROM HumanResources.vEmployee' + CHAR(13);

--Set WHERE clause.
SET @SQLString = @SQLString + N'WHERE LastName LIKE ''D%''';


EXEC sp_executesql @SQLString;


* The declared data type should be ntext/nchar/nvarchar

Tuesday, March 10, 2009

Brief about TSQL (Transact SQL)

Transact SQL is Structure Query Language which is using by SQL Server. When working with Oracle; PL-SQL can be used. A brief about TSQL query language.........

DDL – DATA DEFINITION LANGUAGE
DML – DATA MANIPULATION LANGUAGE
DCL – DATA CONTROL LANGUAGE
TCL – TRANSACT CONTROL LANGUAGE


DDL – CREATE, ALTER, DROP, TRUNCATE

Eg : CREATE DATABASE SampleDatabase
ON
( NAME = MyDatabase,
FILENAME = ‘C:\program files\MyData\mydatabasefile.mdf’,
SIZE = 10MB,
MAXSIZE = UNLIMITED,
FILEGROWTH = 1MB)
LOG ON
( NAME = MyDatabase_LOG,
FILENAME = ‘C:\program files\MyData\mydatabaselog.ldf’,
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB )

Eg :
CREATE TABLE MyTable (
Field1 int PRIMARY KEY,
Field2 char(10) NOT NULL),
Field3 datetime
)

Eg : ALTER DATABASE SampleDatabase
ADD FILE
(
NAME = MyDatabase1,
FILENAME =’c:\program files\MyData\mydatabasefile2.ndf’,
SIZE = 10MB,
MAXSIZE = 50MB,
FILEGROWTH = 1MB
)

Eg : ALTER TABLE MyTable ADD Field4 VARCHAR(10) NULL
ALTER TABLE MyTable DROP COLUMN Field4

Eg : DROP DATABASE SampleDatabase

Eg : DROP TABLE MyTable

DML – SELECT, INSERT, UPDATE, DELETE

SELECT :
Select * from [ABCD]

INSERT :
Insert into ABCD [ColumnA, ColumnB] values 5, 6

Insert into ABCD values 5,6

DELETE
Delete from ABCD where ColumnA = 5

UPDATE
Update ABCD set ColumnA = 8 where ColumnA = 5

DCL – GRANT, REVOKE

CREATE LOGIN [venky] WITH PASSWORD=N'111'
CREATE USER [venky] FOR LOGIN [venky]
EXEC sp_addrolemember N'db_owner', N'venky'
DROP LOGIN [venky]

Grant select to venkat
Revoke select to venkat

TCL – COMMIT, ROLLBACK

Commit
Rollback

CONSTRAINTS IN SQL SERVER

CONSTRAINTS :
Primary Key, Foreign Key,Unique ,Default Key,Check,Null

primary key
NEW TABLE : create table abc (sl int identity(1,1), name varchar(100), constraint PK_sl Primary key(Sl))

ON EXISTING : ALTER TABLE ABC ADD CONSTRAINT pk_sL PRIMARY KEY (SL)

DROPPING : ALTER TABLE ABC DROP CONSTRAINT pk_sL


Foreign Key
NEW TABLE : CREATE TABLE ABCD (SL INT, PLACE VARCHAR(100),DISTRICT VARCHAR(50), CITY VARCHAR(50), CONSTRAINT FK_sl$abc$sl Foreign Key (Sl) references abc(Sl))

ON EXISTING : alter table abcd ADD constraint FK_Sl$abc$sl FOREIGN KEY (SL) REFERENCES ABC(SL)

DROPPNG : alter table abcd drop constraint FK_Sl$abc$sl


unique
NEW TABLE : create table abcde (sl int, rollnum int, classname varchar(10),
Constraint UQ_rollnum Unique(rollnum))

ON EXISTING : ALTER TABLE ABCDE ADD CONSTRAINT uq_ROLLNUM UNIQUE CLUSTERED (ROLLNUM)

DROPPING : ALTER TABLE ABCDE DROP CONSTRAINT UQ_ROLLNUM


check
NEW TABLE : CREATE TABLE ABCDEF (SL INT, AMOUNT INT, CONSTRAINT ch_AMOUNT CHECK(AMOUNT>5))

ON EXISTING : ALTER TABLE ABCDEF ADD CONSTRAINT CH_AMOUNT CHECK(AMOUNT>5)

DROPPING : ALTER TABLE ABCDEF DROP CONSTRAINT CH_AMOUNT


default
CREATE TABLE ABCDEFF (SL INT, MARKS INT DEFAULT 35)

Null / not null