Showing posts with label SQL Server. Show all posts
Showing posts with label SQL Server. Show all posts

Saturday, July 20, 2013

SQL Server performance tips

Does your SQL statement have a WHERE clause?
I know this sounds obvious, but don't retrieve more data than you need. However, less obvious is that even if your SELECT statement retrieves the same quantity of data without a WHERE clause, it may run faster with one.

Is SELECT DISTINCT being used properly?
Again, pretty obvious, but using SELECT DISTINCT where no duplicate records are being returned is an unnecessary performance hit. If you are getting duplicate records, first double check your table joins as this is often the cause and only use the DISTINCT clause if you really need it.

Are you using UNION instead of UNION ALL?
A UNION statement effectively does a SELECT DISTINCT on the results set. If you know that all the records returned are unique from your union, use UNION ALL instead, it is much quicker.

Are your stored procedures prefixed with 'sp_'?
Any stored procedures prefixed with 'sp_' are first searched for in the Master database rather than the one it is created in. This will cause a delay in the stored procedure being executed.

Are all stored procedures referred to as dbo.sprocname?
When calling a stored procedure you should include the owner name in the call, i.e. use EXEC dbo.spMyStoredProc instead of EXEC spMyStoredProc.

Prefixing the stored procedure with the owner when executing it will stop SQL Server from placing a COMPILE lock on the procedure while it determines if all objects referenced in the code have the same owners as the objects in the current cached procedure plan.

Are you using temporary tables when you don't need to?
Although there is sometimes a benefit of using temporary tables, generally they are best eliminated from your stored procedure. Don't assume that retrieving data multiple times is always less efficient than getting the data once and storing it in temporary table as often it isn't. Consider using a sub-query or derived table instead of a temporary table (see examples below). If you are using a temporary table in lots of JOINS in you stored procedure and it contains loads of data, it might be beneficial to add an index to your temporary table as this may also improve performance.

An example of a derived table instead of a temporary table
SELECT COLUMN1, COLUMN2, COUNTOFCOL3
FROM A_TABLE A
INNER JOIN (SELECT COUNT(COLUMN3) AS COUNTOFCOL3, COLUMN2
FROM B_TABLE B
INNER JOIN C_TABLE C ON B.ID = C.ID) ON A.ID = B.ID

Are you using Cursors when you don't need to?
Cursors of any kind slow down SQL Server's performance. While in some cases they are unavoidable, often there are ways to remove them from your code.

Consider using any of these options instead of using a cursor as they are all faster:
•Derived tables
•Sub-queries
•CASE statements
•Multiple queries
•Temporary tables

Are your Transactions being kept as short as possible?
If you are use SQL transactions, try to keep them as short as possible. This will help db performance by reducing the number of locks. Remove anything that doesn't specifically need to be within the transaction like setting variables, select statements etc.

Is SET NO COUNT ON being used?
By default, every time a stored procedure is executed, a message is sent from the server to the client indicating the number of rows that were affected by the stored procedure. You can reduce network traffic between the server and the client if you don't need this feature by adding SET NO COUNT ON at the beginning of your stored procedure.

Are you using IN or NOT IN when you should be using EXISTS or NOT EXISTS?
If you are using IN or NOT IN in a WHERE clause that contains a sub-query you should re-write it to use either EXISTS, NOT EXISTS or perform a LEFT OUTER JOIN. This is because particularly the NOT IN statement offers really poor performance. The example below probably better explains what I mean:

e.g. This SQL statement:

SELECT A_TABLE.COLUMN1
FROM A_TABLE
WHERE A_TABLE.COLUMN2 NOT IN (SELECT A_TABLE2.COLUMN2
FROM A_TABLE2)

Could be re-written like this:
SELECT A_TABLE.COLUMN1
FROM A_TABLE
WHERE NOT EXISTS (SELECT A_TABLE2.COLUMN2
FROM A_TABLE2
WHERE A_TABLE.COLUMN2 = A_TABLE2.COLUMN2)

Do you have a function that acts directly on a column used in a WHERE clause?
If you apply a function to a column used in the WHERE clause of your SQL statement, it is unlikely that the SQL statement will be able to make use of any indexes applied to that column.

e.g.
SELECT A_TABLE.LASTNAME
FROM A_TABLE
WHERE SUBSTRING (FIRSTNAME,1,1) = 'm'

Could be re-written:
SELECT A_TABLE.LASTNAME
FROM A_TABLE
WHERE FIRSTNAME LIKE = 'm%'

Where you have a choice of using the IN or BETWEEN clauses
Use the BETWEEN clause as it is much more efficient

e.g. This SQL statement:

SELECT A_TABLE.NAME
FROM A_TABLE
WHERE A_TABLE.NUMBER IN (100, 101, 102, 103)

Should be re-written like this:
SELECT A_TABLE.NAME
FROM A_TABLE
WHERE A_TABLE.NUMBER BETWEEN 100 AND 103



SQL Server performance tuning can consume a considerable amount of time and effort. The following list is a quick guideline that you should keep in mind when designing and developing SQL Server database applications:

User Defined Functions (UDF)
Refrain from using user defined functions (UDF) in a select statement that may potentially return many records. UDFs are executed as many times as there are rows in a returned result. A query that returns 100,000 rows calls the UDF 100,000 times.

SQL Server table indexes
Create SQL statements that utilize defined table indexes. Using indexes minimizes the amount of table scan which in most cases will be much slower than an index scan.

Multiple disks
The single best performance increase on a SQL Server computer comes from spreading I/O among multiple drives. Adding memory is a close second. Having many smaller drives is better than having one large drive for SQL Server machines. Even though the seek time is faster in larger drives, you will still get a tremendous performance improvement by spreading files, tables, and logs among more than one drive.

Disk controllers
Different disk controllers and drivers use different amounts of CPU time to perform disk I/O. Efficient controllers and drivers use less time, leaving more processing time available for user applications and increasing overall throughput.

SQL Server foreign keys
Ensure that all your tables are linked with foreign keys. foreign keys enhance the performance of queries with joins. Database tables inside each application are naturally related. Islands of tables are rarely needed if your application's business logic is well defined.

SQL Server primary keys
Ensure that every table has a primary key. if you can't find a natural set of columns to serve as a primary key, create a new column and make it a primary key on the table.

Processor (CPU)
When you examine processor usage, consider the type of work the instance of SQL Server is performing. If SQL Server is performing a lot of calculations, such as queries involving aggregates or memory-bound queries that require no disk I/O, 100 percent of the processor's time can be used. If this causes the performance of other applications to suffer, try changing the workload of the queries with aggregates.

Are you doing excessive string concatenation in your stored procedure?
Where possible, avoid doing loads of string concatenation as it is not a fast process in SQL Server.

Have you checked the order of WHERE clauses when using AND?
If you have a WHERE clause that includes expressions connected by two or more AND operators, SQL Server will evaluate them from left to right in the order they are written (assuming that no parenthesis have been used to change the order of execution). You may want to consider one of the following when using AND:
•Locate the least likely true AND expression first. This way, if the AND expression is false, the clause will end immediately, saving time.
•If both parts of an AND expression are equally likely being false, put the least complex AND expression first. This way, if it is false, less work will have to be done to evaluate the expression.

Have you checked that you are using the most efficient operators?
Often you don't have much of a choice of which operator you use in your SQL statement. However, sometimes there is an alternative way to re-write your SQL statement to use a more efficient operator. Below is a list of operators in their order of performance (with the most efficient first).
•=
•>, >=, <, <=
•LIKE
•<>

TempDB Deleted Accidentally


Referred URL
http://www.sqlservercentral.com/articles/Administration/72835/
In famous sci-fi Iron Man series Justin Hammer said "I love peace, but we live in a world of grave threats. Threats that Mr. Stark will not always be able to foresee." The statement is so true for the DBA's world where there are potential threats to data security. There is a constant fear of losing data because of the mistakes of some developer or support person.
This is a scenario I encountered recently and I thought of documenting it. This is a rare situation but we must be ready to face it if it occurs. I had to move the user database files for my TestDB to a new partition on the G:\ drive and I decided to also move tempdb to the G:\ drive at the same time. I used the code below to move the following files.
For TestDB:
Alter Database Testdb Modify File (Name=TestDB, FileName ='G:\Data\TESTDB.MDF')
Alter Database Testdb Modify File (Name=TestDB_log, FileName ='G:\Data\TestDB_log.ldf')

The output of the this code is shown in the screen shot below:

Zoom in  |  Open in new window
For tempdb I executed:
Alter Database tempdb Modify File (Name=tempdev, FileName ='G:\Data\tempdb.mdf')
Alter Database tempdb Modify File (Name=templog, FileName ='G:\Data\templog.ldf')

The output of the that code is shown in the screen shot below:

Zoom in  |  Open in new window
The SQL Server instance was stopped and the files for the user database (TestDB ) were physically moved to the new directory (G:\Data). The tempdb database files are created every time the SQL Server is restarted so there was no need to move those database files. The SQL Server instance was started and then a query was executed on the TestDB as written below.
select name,address into #table from dbo.contact
select * from #table 

The output of the code above is shown in the screen shot below:

Zoom in  |  Open in new window
I had an issue one fine day when I realized that I had run out of space on my workstation's C:\ drive. I went to the Disk Management utility and deleted the G: partition to free up space. I then extended the C: partition. I then tried to open SSMS and found that the SQL Server was not started. I opened up SQL Server Configuration Manager to see the state of the SQL Server. The server was in auto start mode, but it was not running. I tried to start the server, and it did not show any error, but the server did not start. I went to the Windows error log and found the error shown below.
CREATE FILE encountered operating system error 3(The system cannot find the path specified.) while attempting to open or create the physical file 'G:\Data\tempdb.mdf'.
The issue was tempdb database files had been moved to G:\Data\ and that did not exist anymore. When SQL Server tried to restart and create tempdb, it failed. Now I had to bring the SQL Server up somehow and change the file path of tempdb to its default path. To do this, I had to start the SQL Server in single user mode and then make the changes. I stopped the SQL Server Agent from the configuration manager. I opened a command prompt and ran the code below to switch on the SQL Server with minimal configuration.
cd C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn
sqlservr.exe -f
This started the SQL Server in the minimal configuration single user mode as is shown in the screen shot below.

This started SQL Server in single user mode. I opened a new query window in SSMS and connected to the master database and then altered tempdb to point to a physically existing disk folder as shown below.
alter database tempdb move file (filename=tempdev, FileName ='C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\tempdb.mdf')
alter database tempdb move file (filename=templog, FileName ='C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\templog.ldf')

I got the message that the tempdb has been re-configured and that the change will take place when SQL Server is restarted as shown in the screen shot.

Zoom in  |  Open in new window
I closed the query window and the command line that was still running. I started the SQL Server instance again and this time it worked. After the server came up I restored the user database from a backup file using SSMS and executed the same query on the database to find the same result as shown below.






























Zoom in  |  Open in new window

SQL Server & Vb.net Tips

Software for Catching Flash(.swf) from Websites
1) Flash catcher
2) Flash Saver
----------------------------------------------------------------------------------------------------------------------------------
1. How to enable the mnemonics (underline) being displayed when an application is launched?
Usually the underline appears only after you press the Alt Key, but you can enable it by changing the Operating System Settings. On Windows XP, Right Click Desktop to bring up the Display Properties Dialog and then choose Appearance tab and then the Effects Button and uncheck the checkbox "Hide Underlined letters for keyboard navigation until I press the ALT Key".
----------------------------------------------------------------------------------------------------------------------------------
2. An easy way to build connection string.
Though this in not related to .NET directly but it is useful while working with ADO.NET
Collapse1) Open a New notepad and save it with "udl" extension, suppose "New.udl".2) Now you will see that it's icon is changed.3) Open it, you will find Data Link properties dialog box.4) For SQl Server connection string select Microsoft OLE DB Provider For SQL Server in Provider Tab.5) Click button "Next" or select Connection Tab6) Here you can select all connection details and press button Test Connection. If it is successful close this dialog box.7) Now open this file using "Notepad", you will find the connection string. Though it is built for OLE DB type of connection, you can use for SQL Server connection by removing Provider attribute. NOTE: If you are using SQL Authentication with password, then check the checkbox Allow Saving Password.This is necessary so that password appears in connection string.
----------------------------------------------------------------------------------------------------------------------------------
3. How to add a custom or destination folder to SendTo menu?
Every one knows about SendTo menu that appears after right click on any file.By default there are 4 options or destinations in this menu. But you can add custom destinations to this menu. Adding other locations to the Send To menu is convenient if you frequently perform the same file management tasks. For example, if you back up files on another network computer or on same machine where you have to navigate through a deep path every day, having the computer on the Send To menu can save you time.
To add a destination to the Send To menu follow the steps given below:
Open My Computer.
Double-click the drive where Windows is installed (usually drive C, unless you have more than one drive on your computer). If you can't see the items on your drive when you open it, under System Tasks, click Show the contents of this drive.
Double-click the Documents and Settings folder.
Double-click the folder of a specific user.
Double-click the SendTo folder. The SendTo folder is hidden by default. If it is not visible, on the Tools menu, click Folder Options. On the View tab, click Show hidden files and folders.
On the File menu, point to New, and then click Shortcut.
Follow the instructions on your screen.
----------------------------------------------------------------------------------------------------------------------------------
4)Read a text fileThe following sample code uses a StreamReader class to read the System.ini file. The contents of the file are added to a ListBox control. The try...catch block is used to alert the program if the file is empty. There are many ways to determine when the end of the file is reached; this sample uses the Peek method to examine the next line before reading it.

Dim reader As StreamReader = _ New StreamReader(winDir & "\system.ini") Try Me.ListBox1.Items.Clear() Do Me.ListBox1.Items.Add(reader.ReadLine) Loop Until reader.Peek = -1 Catch Me.ListBox1.Items.Add("File is empty") Finally reader.Close() End Try
----------------------------------------------------------------------------------------------------------------------------------

5)Write a text fileThis sample code uses a StreamWriter class to create and write to a file. If you have an existing file, you can open it in the same way.
Dim writer As StreamWriter = _ New StreamWriter("c:\KBTest.txt") writer.WriteLine("File created using StreamWriter class.") writer.Close()
----------------------------------------------------------------------------------------------------------------------------------

6) View file informationThis sample code uses a FileInfo object to access a file's properties. Notepad.exe is used in this example. The properties appear in a ListBox control.
Dim FileProps As FileInfo = New FileInfo(winDir & "\notepad.exe") With Me.ListBox1.Items .Clear() .Add("File Name = " & FileProps.FullName) .Add("Creation Time = " & FileProps.CreationTime) .Add("Last Access Time = " & FileProps.LastAccessTime) .Add("Last Write Time = " & FileProps.LastWriteTime) .Add("Size = " & FileProps.Length) End With FileProps = Nothing
----------------------------------------------------------------------------------------------------------------------------------
7) List disk drivesThis sample code uses the Directory and Drive classes to list the logical drives on a system. For this sample, the results appear in a ListBox control.
Dim dirInfo As Directory Dim drive As String Me.ListBox1.Items.Clear() Dim drives() As String = dirInfo.GetLogicalDrives() For Each drive In drives Me.ListBox1.Items.Add(drive) Next
----------------------------------------------------------------------------------------------------------------------------------

8)List subfoldersThis sample code uses the GetDirectories method of the Directory class to get a list of folders.
Dim dir As String Me.ListBox1.Items.Clear() Dim dirs() As String = Directory.GetDirectories(winDir) For Each dir In dirs Me.ListBox1.Items.Add(dir) Next
----------------------------------------------------------------------------------------------------------------------------------

9)List filesThis sample code uses the GetFiles method of the Directory class to get a list of files.
Dim file As String Me.ListBox1.Items.Clear() Dim files() As String = Directory.GetFiles(winDir) For Each file In files Me.ListBox1.Items.Add(file) Next
----------------------------------------------------------------------------------------------------------------------------------
SQL Server
10) Using add linked server for connecting one server to another external Database server
Connecting Another DB with windows authentication
exec sp_addlinkedserver [intranetbd]

Connecting Another DB with User defined authentication Syntax:

EXEC sp_addlinkedsrvlogin 'Accounts', 'false', NULL, 'SQLUser', 'Password'
Ex:
exec sp_addlinkedsrvlogin [intranetbd],false,'qteam','tsms','Hr'

Accessing the DB serverselect DISTINCT c_id from [intranetbd].Hr.dbo.projects

Found under SQL Server 2005
Server objects -> Linked server
----------------------------------------------------------------------------------------------------------------------------------

11. Sub Query – Query within Query
Ex : select * from EMP Where Id not in (SELECT Max(Id) from EMP group by Name) order by name
----------------------------------------------------------------------------------------------------------------------------------

12. Write query to get 10 records (random wise) from Table, with out use DESC and TOP Command.Query :
select (select count(*) from Empwhere Name <= t.Name) as SRNo,* from Emp t where 11<=(select count(*) from Emp where Name <= t.Name)and 20>=(select count(*) from Emp where Name <= t.Name)order by Name ---------------------------------------------------------------------------------------------------------------------------------- 13. Write query to using Having Statement: ->It can be used with group by and aggregate function like avg, sum, max, min, etc,.
Exampleselect count(Name) from Emp group by Name having count(Name)>1
----------------------------------------------------------------------------------------------------------------------------------
14) using Substring and charindex
CHARINDEX SYNTAX CHARINDEX( text to find, text ) => 11 Example CHARINDEX('SQL', 'Microsoft SQL Server') => 11
SUBSTRING SYNTAX
SUBSTRING ( expression , start , length )
Example
SELECT x = SUBSTRING('abcdef', 2, 3) => bcd

Combined Example – 1 :
SELECT SUBSTRING(email, 1, CHARINDEX('@', email) - 1) AS Email
FROM Active_employee_list
Combined Example – 2 :
select left(mail_id,charindex('@',mail_id)-1) from emp_personal

Result : jayavelcs@gmail.com -> jayavelcs
----------------------------------------------------------------------------------------------------------------------------------

15) using Stored ProcedureA stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. Stored procedures reduce network traffic and improve performance.

Ex 1:CREATE PROCEDURE sp_myStoredProcedureASSelect column1, column2 From Table1

Ex2:CREATE PROCEDURE sp_myStoredProcedure @myInput intASSelect column1, column2 From Table1Where column1 = @myInput

Ex3:CREATE PROCEDURE sp_myStoredProcedure @myInput int, @myString varchar(100), @myFloatAS Ex4:CREATE PROCEDURE sp_myInsert @FirstName varchar(20), @LastName varchar(30)AsINSERT INTO Names(FirstName, LastName)values(@FirstName, @LastName)

Alter Procedurealter procedure

Drop procedureDrop procedure

Executing
Exec sp_myStoredProcedure 0, 'This is my string', 3.45
----------------------------------------------------------------------------------------------------------------------------------
16) Conversion format : Here is the output from the above script:
Type 1:

select * from audit_table where convert(datetime,left(actual_audit_date,11))='09/06/2007'
Type 2:
1) CONVERT(CHAR(19),GETDATE()) ==>Feb 5 2003 5:54AM
2) CONVERT(CHAR(8),GETDATE(),10 ) ==>02-05-03
3) CONVERT(CHAR(10),GETDATE(),110) ==>02-05-2003
4) CONVERT(CHAR(11),GETDATE(),106) ==>05 Feb 2003
5) CONVERT(CHAR(9),GETDATE(),6) ==>05 Feb 03
6) CONVERT(CHAR(24),GETDATE(),113) ==>05 Feb 2003 05:54:39:56
----------------------------------------------------------------------------------------------------------------------------------
17) Using Temp table

Creatingcreate table #tableTmp (empid varchar(50))

Insertinginsert into #tableTmp
select emp_id from Bats_Log_Emp_Revenue where txn_name = 'Add Partner Employee'

Using
select @NoTrans = count(distinct empid) from #tableTmp

Deleting
drop table #tableTmp
----------------------------------------------------------------------------------------------------------------------------------
18) Importing data from Excel to SQL Server
Select Database --> Right mouse click -- > Import data.
The wizard starts and it self-driven.

Through programmatically

SELECT * INTO db1.dbo.table1FROM OPENROWSET('MSDASQL', 'Driver={Microsoft Excel Driver (*.xls)};DBQ=c:\book1.xls', 'SELECT * FROM [sheet1$]')
----------------------------------------------------------------------------------------------------------------------------------
19) Executing exe from SQL Server
declare @cmd varchar(8000)
set @cmd = 'cmd.exe /C "D:\Scheduled Tasks\LinuxBackup.exe "'
EXEC xp_cmdshell @cmd
----------------------------------------------------------------------------------------------------------------------------------
20) Shrink Database Log File Size
USE wss_content;
GO

-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE wss_content
SET RECOVERY SIMPLE;
GO

-- Shrink the truncated log file to 100 MB.
DBCC SHRINKFILE (wss_content_Log, 100);
GO

-- Reset the database recovery model.
ALTER DATABASE wss_content
SET RECOVERY FULL;
GO
----------------------------------------------------------------------------------------------------------------------------------
21) String Functions
LEFT(S , N):
Returns the first N characters of string S from the left.
Example: LEFT('Function',6)='Functi'

RIGHT(S , N) : Returns the last N characters of string S from the right.
Example: RIGHT('Function',6)='nction'

LEN (S): Returns the number of characters in string S.
Example: LEN ('Function',6)=8

LOWER (S): Return string S after converting all characters to lower case.
Example: LOWER ('Function')='function'

UPPER (S): Return string S after converting all characters to upper case.
Example: UPPER ('Function')='FUNCTION'

LTRIM (S): Return string S after removing all blank characters from the left.
Example: LTRIM (' Function')='Function'

RTRIM (S): Return string S after removing all blank characters from the right.
Example: RTRIM ('Function ')='Function'

REPLACE ( S1 ,S2 ,S3 ): Return S1 after replacing all occurrence of S2 in it with S3
Example: REPLACE ('Function','n','123')='Fu123ctio123'

REPLICATE ( S , N): Return a repetition of string S, N times
Example: REPLICATE ('abc',3)='abcabcabc'

REVERSE ( S) : Return string S after reversing the order of all characters.
Example: REVERSE ('Function')=' noitcnuF'

SPACE(N): Return a string of repeated spaces N times.
Example: SPACE(4)=' '

STUFF ( S , I, N, S1): Return string S after deleting N characters from index I and inserting S1 at position I.
Example: STUFF ('Function', 3, 4,'abc' )='Fuabcon'

SUBSTRING ( S, I, N): Return a portion of S from index I of N characters.
Example: SUBSTRING ('Function', 3, 4)='ncti'
------------------------------------------------------------------------------------------------------------------------------------------
1) Aggregate FunctionsAVG ( [ ALL DISTINCT ] E ) : Return the average of not null values of expression E. If ALL parameter is specify the function is apply to all values, it is the default value. If DISTINCT parameter is specify the function is apply only on each occurrence of the value.
Example: SELECT HOURS FROM Employee returns (7, 8, 10, 5, 4, 6, 8, 7, 11, 10, 12) SELECT AVG(HOURS) FROM Employee returns (8) SELECT AVG(DISTINCT HOURS) FROM Employee returns (7)

COUNT ( [ ALL DISTINCT ] E ]) : Return the number of item in the group of expression E. If E=* the function will return the number of record in the data source. If ALL parameter is specify the function is apply to all values, it is the default value. If DISTINCT parameter is specify the function is apply only on each occurrence of the value. The parameter ALL and DISTINCT can not be use with *.
MAX(E): Return the maximum value of expression E.
Example: SELECT HOURS FROM Employee returns (7, 8, 10, 5, 4, 6, 8, 7, 11, 10, 12) SELECT MAX(HOURS) FROM Employee return (12)

MIN(E): Return the minimum value of expression E.
Example: SELECT HOURS FROM Employee returns (7, 8, 10, 5, 4, 6, 8, 7, 11, 10, 12)
SELECT MIN(HOURS) FROM Employee return (4)
SUM ( [ ALL DISTINCT ] E): Return the SUM of not null values of expression E. If ALL parameter is specify the function is apply to all values, it is the default value. If DISTINCT parameter is specify the function is apply only on each occurrence of the value. SUM can be use numeric columns only.
Example: SELECT HOURS FROM Employee returns (7, 8, 10, 5, 4, 6, 8, 7, 11, 10, 12) SELECT SUM(HOURS) FROM Employee returns (88) SELECT SUM(DISTINCT HOURS) FROM Employee returns (63)
------------------------------------------------------------------------------------------------------------------------------------------
29) Using Data type Conversations
Explicitly converts an expression of one data type to another. CAST and CONVERT provide similar functionality.

Syntax
CAST ( expression AS data_type )
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

Ex:CONVERT(decimal(10,5), @myval)
------------------------------------------------------------------------------------------------------------------------------------------
27) Try –Catch

BEGIN TRY
EXEC dbo.sp_bcr_import_data_report
END TRY
BEGIN CATCH
PRINT 'Test';
RETURN;
END CATCH
------------------------------------------------------------------------------------------------------------------------------------------
28) Begin Tran – End Tran

go
begin tran mytrans;
insert into table1 values (1, 'test');
insert into table1 values (1, 'jsaureouwrolsjflseorwurw'); -- it will encounter error here since max value to be inputted is 10
commit tran mytrans;
go

SQL SERVER – Select the Most Optimal Backup Methods for Server

Backup and Restore are very interesting concepts and one should be very much with the concept if you are dealing with production database. One never knows when a natural disaster or user error will surface and the first thing everybody wants is to get back on point in time when things were all fine. Well, in this article I have attempted to answer a few of the common questions related to Backup methodology.
How to Select a SQL Server Backup Type
In order to select a proper SQL Server backup type, a SQL Server administrator needs to understand the difference between the major backup types clearly. Since a picture is worth a thousand words, let me offer it to you below.

Select a Recovery Model First
The very first question that you should ask yourself is: Can I afford to lose at least a little (15 min, 1 hour, 1 day) worth of data? Resist the temptation to save it all as it comes with the overhead – majority of businesses outside finances can actually afford to lose a bit of data.
If your answer is YES, I can afford to lose some data – select a SIMPLE (default) recovery model in the properties of your database, otherwise you need to select a FULL recovery model.
The additional advantage of the Full recovery model is that it allows you to restore the data to a specific point in time vs to only last backup time in the Simple recovery model, but it exceeds the scope of this article
Backups in SIMPLE Recovery Model
In SIMPLE recovery model you can select to do just Full backups or Full + Differential.
Full Backup
This is the simplest type of backup that contains all information needed to restore the database and should be your first choice. It is often sufficient for small databases, but note that it makes a big impact on the performance of your database
Full + Differential Backup
After Full, Differential backup picks up all of the changes since the last Full backup. This means if you made Full, Diff, Diff backup – the last Diff backup contains all of the changes and you don’t need the previous Differential backup. Differential backup is obviously smaller and carries less performance overhead
Backups in FULL Recovery Model
In FULL recovery model you can select Full + Transaction Log or Full + Differential + Transaction Log backup. You have to create Transaction Log backup, because at that time the log is being truncated. Otherwise your Transaction Log will grow uncontrollably.
Full + Transaction Log Backup
You would always need to perform a Full backup first. Then a series of Transaction log backup. Note that (in contrast to Differential) you need ALL transactions to log since the last Full of Diff backup to properly restore. Transaction log backups have the smallest performance overhead and can be performed often.
Full + Differential + Transaction Log Backup
If you want to ease the performance overhead on your server, you can replace some of the Full backup in the previous scenario with Differential. You restore scenario would start from Full, then the Last Differential, then all of the remaining transactions log backups
Typical backup Scenarios
You may say “Well, it is all nice – give me the examples now”. As you mayalready know, my favorite SQL backup software is SQLBackupAndFTP. If you go to Advanced Backup Schedule form in this program and click “Load a typical backup plan…” link, it will give you these scenarios that I think are quite common – see the image below.

The Simplest Way to Schedule SQL Backups
I hate to repeat myself, but backup scheduling in SQL agent leaves a lot to be desired. I do not know the simple way to schedule your SQL server backups than in SQLBackupAndFTP – see the image below. The whole backup scheduling with compression, encryption and upload to a Network Folder / HDD / NAS Drive / FTP / Dropbox / Google Drive / Amazon S3 takes just a few minutes – see my previous post for the review.
Referred URL















http://blog.sqlauthority.com/2012/12/18/sql-server-select-the-most-optimal-backup-methods-for-server/