Professional Documents
Culture Documents
1.
2.
3.
4.
5.
6.
7.
8.
9.
SERVERPROPERTY
OBJECT_ID
NULLIF
ISDATE
BOLEAN VALUES 1=TRUE 0=FALSE
ISNUMERIC
BOLEAN VALUES 1=TRUE 0=FALSE
COALESCE
ISNULL
ASCII
SOUNDEX Returns a four-character (SOUNDEX) code to evaluate the
similarity of two strings.
10.
11.
12.
13.
SELECT CHAR(65)
SELECT CHAR(9) --> Tab
SELECT CHAR(10) --> Line feed
SELECT CHAR(13) --> Carriage return
14. RTRIM
15. LTRIM
16. PATINDEX Returns the starting position of the first occurrence of a pattern
in a specified expression, or zeros if the pattern is not found, on all
valid text and character data types.(REGULAR EXPRESSION CAN BE USE)
17. CHARINDEX Searches expression2 for expression1 and returns its starting
position if found if not found returns 0.
18. SPACE Returns a string of repeated spaces.
19. STR Returns character data converted from numeric data.
SELECT STR(123.673,7, 2);
20.
21. DIFFERENCE Returns an integer value that indicates the difference between
two character expressions
22. REPLACE Replaces all occurrences of a specified string value with another
string value. SELECT REPLACE('abcdefghicde','cde','---');
23. STUFF The STUFF function inserts a string into another string.
SELECT STUFF('abcdef', 2, 3, '---').
24. LEFT Returns the left part of a character string with the specified number
of characters.
25. RIGHT Returns the right part of a character string with the specified number
of characters.
26. REPLICATE Repeats a string value a specified number of times.
27. LEN Returns the number of characters of the specified string expression,
excluding trailing blanks.
28. REVERSE
29. LOWER
30. UPPER
1. CONVERT
2. CAST
SELECT CAST(23 AS char(20))
select
SELECT
SELECT
SELECT
GETDATE()
CONVERT(char(20),GETDATE(),112)
CONVERT(char(20),GETDATE(),113)
CONVERT(char(20),GETDATE(),101)
------------------------------Compound Operators------------------------------SQL Server 2008 introduces the Compound Operators as a programmability enhancement in
--Transact-SQL. Compound operators execute some operation, such as +, -, * and /, and
set
--an original value to the result of the operation.
SET @Index = @Index + 1
SET @Index += 1
---------------Row Constructor (or Table-Valued Constructor)--------------------One limitation of the row constructor is the maximum number of rows that can be
-inserted, which is 1000 rows.
SELECT *
FROM (VALUES ('USD', 'U.S. Dollar'),
('EUR', 'Euro'),
OUTPUT OBJECT
DELETE FROM EMP
OUTPUT DELETED.*
DELETE FROM EMP_SET
OUTPUT DELETED.ENAME,deleted.HIREDATE
WHERE COMM IS NULL
-------------------------------------------RANK-----------------------------------1.
2.
3.
4.
5.
6.
7.
ROW_NUMBER () OVER
RANK() OVER
NTILE() OVER
DENSE_RANK() OVER
DERIVED TABLE
CTE COMMON TABLE EXPRESSION
GROUPING SETS
------------------------------------DATA TYPES-----------------------------------------------1.
2.
3.
4.
UNIQUEIDENTIFIER
NVARCHAR(MAX)
VARCHAR(MAX)
VARBINARY(MAX)
5. DATE
This is new data type introduce in Sqlserver 2008 before we were using DATETIME,
SMALLDATETIME Data type it was showing us 12:00 am even if we just to store date only. (check
constraint and data type topic)
6.
TIME
7.
8.
9.
DATETIMEOFFSET
DATETIME2
USER-DEFINE TABLE TYPE you can create a user-defined table type which
represents the definition of a table structure.(CHECK OUT CONSTRAINT AND
DATATYPES)
1.
2.
3.
4.
5.
6.
7.
8.
9.
1.
2.
3.
4.
5.
--------------------------------TRIGGERS------------------------------
1.
2.
3.
4.
DDL
DML
INSTEAD_OF_TRIGGERS
RAISEERROR
DDL TRIGGERS
6. CREATE TRIGGER ABC_TEST ON DATABASE
FOR CREATE_TABLE
7. CREATE TRIGGER ABC_TEST ON ALL SERVER
FOR CREATE_TABLE
SELECT * FROM sys.triggers
SELECT * FROM sys.trigger_events
1. INSTEAD_OF TRIGGERS
Sp_spaceused
sys.dm_db_file_space_usage
sys.dm_db_task_space_usage
sys.dm_exec_requests
Internal objects are created internally by SQL Server. Applications cannot directly
insert into or delete rows from
internal objects. Internal object metadata is stored in memory. The metadata does
not appear in system catalog views
such as sys.all_objects. Internal objects are considered to be hidden objects.
User objects appear in catalog views such as sys.all_objects. Sp_spaceused can show the
size occupied by these objects. User
objects include both user-defined tables and indexes, and system catalog tables
and indexes. These two types of tables have
exactly the same data structure on disk. User-defined tables can be manipulated by
Transact-SQL.
-----------------------Monitoring I/O-----------------------You can identify I/O bottlenecks by monitoring the following perfmon counters for
physical devices associated with tempdb.
1) PhysicalDisk Object: Avg. Disk Queue Length: The average number of physical read and
write requests that were queued
on the selected physical disk during the sampling period. If the I/O system is
overloaded, more read/write operations
will be waiting. If the disk queue length exceeds a specified value too frequently
during peak usage of SQL Server,
there might be an I/O bottleneck.
2)Avg. Disk Sec/Read: The average time, in seconds, of a read of data from the disk. Use
the following to analyze numbers
in the output.
Less than 10 milliseconds (ms) = very good
Between 10-20 ms = okay
Between 20-50 ms = slow, needs attention
Greater than 50 ms = serious IO bottleneck
3)Avg. Disk Sec/Write: The average time, in seconds, of a write of data to the disk. See
the guidelines for the previous
item, Avg. Disk Sec/Read.
4)Physical Disk: %Disk Time: The percentage of elapsed time that the selected disk drive
was busy servicing read or write
requests. A general guideline is that if this value > 50%, there is an I/O
bottleneck.
5)Avg. Disk Reads/Sec: The rate of read operations on the disk. Make sure that this
number is less than 85% of disk capacity.
6)Avg. Disk Writes/Sec: The rate of write operations on the disk. Make sure that this
number is less than 85% of the disk capacity.
7)Database: Log Bytes Flushed/sec: The total number of log bytes flushed. A large value
indicates heavy log activity in tempdb.
8)Database:Log Flush Waits/sec: The number of commits that are waiting on log flush.
Although transactions do not wait for the
log to be flushed in tempdb, a high number in this performance counter indicates
and I/O bottleneck in the disk(s) associated
with the log.
9)If SQL Server is configured with insufficient memory, it incurs more I/O overhead. You
can examine following perfmon counters
to identify memory pressure:
1)Buffer Cache hit ratio
2)Page Life Expectancy
3)Checkpoint pages/sec
4)Lazywrites/sec
--------------------------------JOINT HINTS-------------------------------1.
2.
3.
Looping
Hashing
Merging
--------------------------------TABLE HINTS-------------------------------1.
There is a lot different king of TABLE HINTS like (updatelock, nowait, ignore
triggers, ignor_constraints and many more )
The method to use table hints is after the table we have to specify WITH Clause
(here we have to specify key word of hints)
--------------------------------QUERY HINTS-------------------------------2.
Unspecified level
ReadUncomitted
ReadCommitted
Repeatable Read
5.
6.
7.
8.
9.
Serializable
Snapshot
Naming Transaction
Marking Transaction
Distributing Transaction
@@TRANCOUNT >0
------------XACT_STATE()-----------------Values for
1 =
back.
0 =
-1 =
When XACT_ABORT is turned ON, all errors are fatal and there for value of XACT_STATE()
will always be -1
-------------------SET XACT_ABORT ON----------------------When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the
entire transaction is terminated and rolled back.
When SET XACT_ABORT is OFF, in some cases only the Transact-SQL statement that raised
the error is rolled back and the transaction continues processing. Depending upon the
severity of the error, the entire transaction may be rolled back even when SET
XACT_ABORT is OFF. OFF is the default setting.
----------------------FULL BACKUPS-----------------------OPTIONS
1. FORMAT
2. NOFORMAT
3. INIT
(Overwrite to backup set)
4. NOINIT
(default append to existing backup set)
5. NORECOVERY
6. STANDBY
7. NOSKIP
8. SKIP
9. NOREWIND
10.
NOUNLOAD
11.
COMPRESSION
12.
STATS
13.
CHECKSUMS
14.
COPY_ONLY
15.
PASSWORD
16.
EXPIREDATE
17.
NO_TRUNCATE
Full backup
Differential backup
File Group Backup
{ NOINIT | INIT }
Controls whether the backup operation appends to or overwrites the existing backup
sets on the backup media. The default is to append to the most recent backup set on
the media (NOINIT).
SELECT * FROM sysfilegroups
Select * from sysfilegroups
------------Moving database object from one file group to another----------We can move objects from on file groups to another using drop constraint
command with (move to .......) command
----------------------COPY ONLY BACKUP ---------------------Its totally independent from the sequence of conventional SQLSERVER backup type.
--------------------------------------PARTIAL BACKUP-------------------------------------A partial backup does not contain all the filegroups. Instead,
a partial backup contains all the data in the primary filegroup, every read/write
filegroup, and any optionally-specified read-only files.
Partial backups are useful whenever you want to exclude read-only filegroups.
A partial backup of a read-only database contains only the primary filegroup.
Partial backups are not supported by SQL Server Management Studio or the Maintenance
Plan Wizard.
----------------Tail log backup--------------A tail log backup is the last Transaction log backup that you make prior to restoring
a database. What this means is that if your DB crashes for whatever reason, you to
backup your Transaction log so that you can do point in time recovery.
This last Backup is called tail Log Backup.
If your data file (MDF) is unavailable you need to use WITH NO_TRUNCATE option.
----------------------RESTORATION------------------------1.
2.
3.
4.
5.
FULL RESTORE
PARTITAL RESTORE
FILE RESTORE
PAGE RESTORE
TRANSACTION LOG RESTORATION
use msdb
select *
select *
select *
select *
select *
select *
select *
select *
1.
2.
3.
4.
5.
6.
7.
from
from
from
from
from
from
from
from
backupfile
backupfilegroup
backupmediafamily
backupmediaset
backupset
restorefile
restorefilegroup
msdb.dbo.restorehistory
Full Restore
Differential Restore
Restore with RECOVERY OPTION
Restore with NORECOVERY OPTION
Restore with MOVE option
Restore with STOPAT option point in time
Restore Transaction to a MARK using STOPATMARK option
-------------Rebuild System Databases Procedure ------------------1.Insert the SQL Server 2008 installation media into the disk drive, or, from a command
prompt, change directories
--to the location of the setup.exe file on the local server. The default location
on the server is C:\Program Files
--\Microsoft SQL Server\100\Setup Bootstrap\Release.
--2.From a command prompt window, enter the following command. Square brackets are used
to indicate optional parameters. Do not enter the brackets.
-------------------CURSOR EXAMPLE--------------1.
2.
3.
4.
5.
6.
7.
DECLARE CURSOR
OPEN CURSOR
IF @@CURSOR_ROWS > 0
FETCH NEXT FROM
WHILE FETCH_STATUS = 0
CLOSE CURSOR
DEALLOCATE CURSOR
-----------------------MERGE-----------------------
1.
2.
3.
4.
5.
MERGE
USING (STATEMENT) ON =
WHEN MATCHED AND > < = OR THEN DELETE
WHEN MATCHED THEN UPDATE SET =
WHEN NOT MATCHED THEN
------------------------PARTITION TABLE------------------------------1. Create a partition function to specify how a table or index that uses the
function can be partitioned.
2. Create a partition scheme to specify the placement of the partitions of a
partition function on filegroups.
3. Create a table or index using the partition scheme.
---------------------INDEXES--------------------1.
2.
3.
4.
5.
6.
7.
8.
FILLFACTOR
SORT_IN_TEMPDB
IGNORE_DUP_KEY
STATISTICS_NORECOMPUTE
DROP_EXISTING
ONLINE (ON,OFF)
ALLOW_ROW_LOCKS
8. ALLOW_PAGE_LOCKS
9. MAXDOP
10.
DATA_COMPRESSION
11.
ON PARTITIONS
-------------------------------Clustered Index----------------------------A Clustered table has its data pages linked, making sequential scans a bit faster.
Clustered indexes sort and store the data rows in the table based on their key values.
There is only can one clustered Index because data pages can be sorted in one order.
With primary key constraint its create a Unique Clustered Index.
When we create UNIQUE constraint, a Unique non-clustered index is created to enforce a
UNIQUE constraint by default.
6. If CLUSTERED Index is Created/Rebuild on a heap with several existing non-clustered
Indexes, all the non-clustered indexes must be rebuild so its can contains the Clustering
key values instead of RID (row identifier).
1.
2.
3.
4.
5.
-------------------------Non Clustered Indexes ---------------------1. Non-clustered indexes are created to improve the performance of
frequently used queries not covered by the clustered index.
2. When you create a UNIQUE constraint, a unique non-clustered index is
created to enforce a UNIQUE constraint by default.
3. By default, a non-clustered index is created if Clustered is not
specified.
4. After a unique clustered index has been created on a view, nonclustered indexes can be created.
5. Each table can have up to 999 non-clustered indexes.
6. When a Unique non-clustered index exists, the Database Engine checks
for duplicate values each time data is added by insert operations.
7. The leaf Level of non-clustered index is made up of index pages instead
of data pages.
8. When a non-clustered index is disabling, the index data rows are
deleted, but the index definition remains in metadata. The index is
enable when its is rebuilt.
9. When the non-clustered index is not disabled, the rebuild operation
requires enough temporary disk space to store both the old and new
index.
10.
When a non-clustered index is disabled and the non-clustered
index is on the primary key, any active, referencing Foreign Key
constraints will automatically be disable, these constraints must be
manually enable after the index is rebuilt.
Index Further Types
Covered Index
Filtered index
Partition index
Compressed index
To find heap tables
--------DBCC SHOWCONFIG to find Index Fragmentation-------DBCC SHOWCONFIG displays Fragmentation information for the data and indexes of the
specified table or view, if the specified table or index is partitioned, DBCC SHOWCONFIG only
displays the first partition of the specified table or index
DBCC SHOWCONFIG (PRODUCTION.PRODUCT, 1) WITH FAST;
DBCC SHOWCONFIG (PRODUCTION.PRODUCT);
Select OBJECT_NAME(1547152557)
Select DB_name(9)
Select DB_id('ADVENTUREWORKS')