Friday, May 6, 2011

FUNCTIONS IN SQLSERVER

Functions In SSQL SERVER
We have 2 types of functions in sql server.They are
1.System Functions---Builtin functions
2.Userdefined Functions
We can differentiate built-in functions Following .
1.Single Row Functions
2.Group Functions
Singlerow Functions
Ø  Mathematical Functions
Ø  Strimg Functions
Ø  Date  and Time functions
Matheatical Functions
1.ABS
select ABS(10)
select ABS(-10)
Select ABS(0)
2.Ceiling
            Select Ceiling(15.6)
            Select Ceiling (15.2)
            Select Ceiling(15.0)
3.Floor
            Select floor(15.6)
            Select floor(15.2)
            Select floor(15.0)
4.Log(n)
            Select log(10)
            Select log(2)
5.Log10
            Select log10(10)
            Select log10(2)
6.PI
            Select PI()
7.Power(n,m)
            Select POWER(10,3)
            Select POWER(2,3)
8.RAND([SEED])
Select RAND()
            Select RAND(100)
9.ROUND(n,length,[,Function])
            Select ROUND(1546.561,2)
            Select ROUND(1546.561,1)
            Select ROUND(1546.561,0)
            Select ROUND(1546.561,-1)
            Select ROUND(1546.561,2,1)
            Select ROUND(1546.561,-2,1)
10.SIGN(n)
            Select SIGN(100)
            Select SIGN(0)
            Select SIGN(-100)
11.SQRT(n)
            Select SQRT(25)
12.SQUARE(n)
            Select SQUARE(5)
13.In Addition we have some tagnometric Functions like SIN,COS,TAN,ACOS,ASIN,ATAN
String Functions
1.ASCII(s)
            Select ASCII(‘A’)
2. CHAR(‘n’)
            Select CHAR(‘100’)
3. NCHAR(’n’)
            Select NCHAR(‘97’)
4.CHARINDEX(SearchExp,StringExp,[Start location])
            Select CHARINDEX(‘o’,’HELLO’,2)
5.LEFT(s,n)
            Select LEFT(‘HELLO’,3)
6.RIGHT(S,N)
            Select RIGHT(‘HELLO’,3)
7.SUBSTRING(S,Start,Length)
            Select SUBSTRING(‘HELLO’,1,5)
8.LEN(S)
            Select LEN(‘KRISH’)
9.LOWER(S)
            Select LOWER(‘kRIsh’)
10.UPPER(S)
            Select UPPER(‘JaNu’)
11.LTRIM(S)
            Select LEN(LTRIM(‘  HELLO’))
            Select  ‘Hello’+LTRIM(‘    WORLD’)
12.RTRIM(S)
            Select LEN(RTRIM(‘ HELLO        ’))
            Select  ‘Hello’+RTRIM(‘    WORLD          ’)
13.REPLACE(S1,S2,S3)
            Select REPLACE(‘HELLO’,’L’,’X’)
14.REPLICATE(S,N)
            Select REPLICATE(‘KRISH’,3)
15.REVERSE(S)
            Select REVERSE(‘HELLO’)
16.SOUNDEX(S)
            Select SOUNDEX(‘Smith’),SOUNDEX(‘Smyth’)
17.DIFFERENCE(S1,S2)
            Select DIFFERENCE (‘SMITH’,’SMYTH’)
18.SPACE(n)
            Select ‘Hello’ + SPACE(3)+’WORLD’
19.STUFF(S,Start,Length,Replace-Str)
            Select STUFF(‘ABXXCDXX’,3,3,’yy’)
Date and Time Functions
1.GETDATE()
            Select GETDATE()
2.DAY(DATE)
            Select DAY(GETDATE())
            Select DAY(‘05/05/2010’)
3.MONTH(DATE)
            Select MONTH(GETDATE())
            Select MONTH(’05/04/87’)
4.YEAR(DATE)
            Select YEAR(GETDATE())
            Select YEAR(‘05/07/1987’)
5.DATENAME(Datepart,date)
            Select DATENAME(mm,’10/24/78’)
            Select DATENAME(dd,’10/24/78’)
6.DATEPART(Datepart,Date)
7.DATEADD(Datepart,number,date)
            Select DATEADD(DD,30,GETDATE())
            Select DATEADD(MM,10,GETDATE())
8.DATEDIFF(DATEPART,STARTDATE,EndDate())
            Select DATEDIFF(yy,’10/04/1987’.,05/01/2011’)
9.GETUTCDATE()
            Select GETUTCDATE()
Conversion Functions
1.CAST(Expression AS DataType[(Length)]
            Select CAST(10.6496 AS INT)
            Select CAST(10.349787 AS MONEY)
2.CONVERT(DataType[Length],Expression [,Style])
            Select CONVERT(INT,10.67789)
            Select CONVERT(VARCHAR(50),GETDATE())
            Select  CONVERT(VARCHAR(50),GETDATE(),101)
System Functions
1.ISNUMERIC (EXPRESSION)
            SEELCT  ISNUMERIC(100)
            SELECT ISNUMERIC(‘100’)
            SELECT ISNUMERIC(‘100A’)
2.ISDATE(EXPRESSION)
            SELECT ISDATE(’15/14/2011’)
3.ISNULL(EXPRESSION1,EXPRESSION2)
            SEELCT  ISNULL(100,200)
            SEELCT ISNULL(NULL,200)
4.COALESCE(EXPRESSION1,EXPRESSION2,………EXPRESSIONN)
            SEELCT COALESCE(NULL,100,NULL,200)
5.DATALENGTH(EXPRESSION)
SELECT  DATALENTH(100)
SELCT DATALENGHT(‘HELLO’)
6.HOST_NAME()
            SELECT HOST_NAME()
7.IDENT_CURRENT(‘TABLENAME’)
            SEELCT IDENT_CURRENT(‘BANK’)
8.IDENT_SEED(‘TABLENAME’)
            SELECT IDENT_SEED(‘BANK’)
9.IDENT_INCR(‘TABLENAME’)
            SEELCT IDENT_INCR(‘BANK’)
10.NEWID()
            SELECT NEWID()
11.NULLIF(EXPRESSION1,EXPRESSION2)
            SELECT NULLIF(100,200)
            SELECT NULLIF(100,100)
13.APP_NAME()
14.CASE
GROUP FUNCTIONS
1.COUNT(EXPRESSION)
            SELECT COUNT(*) FROM EMP
2.SUM(EXPRESSION)
            SELECT SUM(SAL) FROM EMP
3.AVG(EXPRESSION)
            SELECT AVG(SAL)  FROM EMP
4.MAX(EXPRESSION)
            SEELCT MAX(SAL) FROM EMP
5.MIN(EXPRESSION)
            SEELCT MIN(SAL) FROM EMP
6.STDEV(EXPRESSION)
          

DBCC COMMANDS WITH EXAMPLES

SQL Server – DBCC Commands

DBCC (Database consistency checker) are used to check the consistency of the databases. The DBCC commands are most useful for performance and trouble shooting exercises.
I have listed down and explained all the DBCC commands available in SQL Server 2005, with examples.
The DBCC Commands broadly falls into four categories:
Ø  Maintenance
Ø  Informational
Ø  Validation
Ø  Miscellaneous
v  Maintenance Commands
Performs maintenance tasks on a database, index, or filegroup.
1. CLEANTABLE – Reclaims space from the dropped variable-length columns in tables or index views.
DBCC CLEANTABLE (‘AdventureWorks’,'Person.Contact’,0)
2. DBREINDEX – Builds one or more indexes for the table in the specified database. (Will be removed in the future version, use ALTER INDEX instead)
USE AdventureWorks
DBCC DBREINDEX (‘Person.Contact’,'PK_Contact_ContactID’,80)
3. DROPCLEANBUFFERS – Removes all clean buffers from buffer pool.
DBCC DROPCLEANBUFFERS
4. FREEPROCCACHE – Removes all elements from the procedure cache
DBCC FREEPROCCACHE
5. INDEXDEFRAG – Defragments indexes of the specified table or view.
DBCC INDEXDEFRAG (‘AdventureWorks’, ‘Person.Address’, PK_Address_AddressID)
6. SHRINKDATABASE – Shrinks the size of the data and log files in the specified database
DBCC SHRINKDATABASE (‘AdventureWorks‘, 10)
7. SHRINKFILE – Shrinks the size of the specified data or log file for the current database or empties a file by moving the data from the specified file to other files in the same filegroup, allowing the file to be removed from the database.
USE AdventureWorks;
– Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (AdventureWorks_Log, 1)
8. UPDATEUSAGE – Reports and corrects pages and row count inaccuracies in the catalog views.
DBCC UPDATEUSAGE (AdventureWorks)Informational Commands
v  Informational Commands
              Performs tasks that gather and display various types of information.
1. CONCURRENCYVIOLATION – is maintained for backward compatibility. It runs but returns no data.
DBCC CONCURRENCYVIOLATION
2. INPUTBUFFER – Displays the last statement sent from a client to an instance of Microsoft SQL Server 2005.
DBCC INPUTBUFFER (52)
3. OPENTRAN – Displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the specified database.
DBCC OPENTRAN;
4. OUTPUTBUFFER – Returns the current output buffer in hexadecimal and ASCII format for the specified session_id.
DBCC OUTPUTBUFFER (52)
5. PROCCACHE – Displays information in a table format about the procedure cache.
DBCC PROCCACHE
6. SHOW_STATISTICS – Displays the current distribution statistics for the specified target on the specified table
USE AdventureWorks
DBCC SHOW_STATISTICS (‘Person.Address’, AK_Address_rowguid)
7. SHOWCONTIG – Displays fragmentation information for the data and indexes of the specified table or view.
USE AdventureWorks
DBCC SHOWCONTIG (‘HumanResources.Employee’);
8. SQLPERF – Provides transaction log space usage statistics for all databases. It can also be used to reset wait and latch statistics.
DBCC SQLPERF(LOGSPACE)
9. TRACESTATUS – Displays the status of trace flags.
DBCC TRACESTATUS(-1)
10. USEROPTIONS – Returns the SET options active (set) for the current connection.
DBCC USEROPTIONS
v  Validation Commands
Performs validation operations on a database, table, index, catalog, filegroup, or allocation of database pages.
1. CHECKALLOC – Checks the consistency of disk space allocation structures for a specified database.
DBCC CHECKALLOC (AdventureWorks)
2. CHECKCATALOG – Checks for catalog consistency within the specified database.
DBCC CHECKCATALOG (AdventureWorks)
3. CHECKCONSTRAINTS – Checks the integrity of a specified constraint or all constraints on a specified table in the current database.
DBCC CHECKCONSTRAINTS WITH ALL_CONSTRAINTS
4. CHECKDB – Checks the logical and physical integrity of all the objects in the specified database.
DBCC CHECKDB (AdventureWorks)
5. CHECKFILEGROUP – Checks the allocation and structural integrity of all tables and indexed views in the specified filegroup of the current database.
USE AdventureWorks
DBCC CHECKFILEGROUP
6. CHECKIDENT – Checks the current identity value for the specified table and, if it is needed, changes the identity value.
USE AdventureWorks;
DBCC CHECKIDENT (‘HumanResources.Employee’)
7. CHECKTABLE – Checks the integrity of all the pages and structures that make up the table or indexed view.
USE AdventureWorks;
DBCC CHECKTABLE (‘HumanResources.Employee’)
v  Miscellaneous Commands
Performs miscellaneous tasks such as enabling trace flags or removing a DLL from memory.
1. dllname (FREE) – Unloads the specified extended stored procedure DLL from memory.
DBCC xp_sample (FREE)
2. TRACEOFF – Disables the specified trace flags.
DBCC TRACEOFF (3205)
3. HELP – Returns syntax information for the specified DBCC command.
– List all the DBCC commands
DBCC HELP (‘?’)
– Show the Syntax for a given DBCC commnad
DBCC HELP (‘checkcatalog’)
4. TRACEON – Enables the specified trace flags.
DBCC TRACEON (3205)