11+ Year IT Industry Experience, Working as Technical Lead with Capgemini | Consultant | Leadership and Corporate Trainer | Motivational and Technical Speaker | Career Coach | Author | MVP | Founder Of RVS Group | Trained more than 4000+ IT professionals | Azure | DevOps | ASP.NET | C# | MVC | WEB API | ANGULAR | TYPESCRIPT | MEAN | SQL | SSRS | WEB SERVICE | WCF... https://bikeshsrivastava.blogspot.in/ http://bikeshsrivastava.com/
Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts
Friday, September 2, 2016

Create sql server database backup(.BAK) file using sql server job agent.

In This Article i am going to describes how to create a SQL Server Agent job step that executes SQL scripts in SQL Server 2012 by using SQL Server Management Studio,I am giving you a example to take backup (.BAK) file of sql server database on daily basis at some specific time which is given in job scheduler.
SQL Server Management Studio can be used to create a database backup  job to  take backup of an user database. Just following some steps and UI work process to create a simple backup job, run the job and you can see the results on screen.
Step 1:- SQL Server Management Studio and login with your credential.
Step 2:- After connect to sql server,Expand object explorer=>sql server agent=>Exapnd Job=>Right click=>select in menu "New job".see image..
Step 3:- Select General=>type name of sql agent job,you can write description also. see image....

 Step 4:- Select Steps=>Click "New"=>"OK" on bottom of screen.see image....
After click on new open new tab see in next screen. 

Step 5:- Select General=>type Step name=>Command ,In command panel you can use sql query.see image...
Here my query is use to take backup of sql database.I have created a cursor to take backup file of database.
  1. DECLARE @name VARCHAR(50) -- database name      
  2. DECLARE @path VARCHAR(256) -- path for backup files      
  3. DECLARE @fileName VARCHAR(256) -- filename for backup      
  4. DECLARE @fileDate VARCHAR(20) -- used for file name    
  5.     
  6.      
  7. -- specify database backup directory    
  8. SET @path = 'C:\Backup\'      
  9.     
  10.      
  11. -- specify filename format    
  12. SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)     
  13.     
  14.      
  15. DECLARE db_cursor CURSOR FOR      
  16. SELECT name     
  17. FROM master.dbo.sysdatabases     
  18. WHERE name IN ('TestDB')    
  19.      
  20. OPEN db_cursor       
  21. FETCH NEXT FROM db_cursor INTO @name       
  22.     
  23.      
  24. WHILE @@FETCH_STATUS = 0       
  25. BEGIN       
  26.        SET @fileName = @path + @name + '_' + @fileDate + '.BAK'      
  27.        BACKUP DATABASE @name TO DISK = @fileName      
  28.      
  29.        FETCH NEXT FROM db_cursor INTO @name       
  30. END       
  31.     
  32.      
  33. CLOSE db_cursor       
  34. DEALLOCATE db_cursor     

Step 6:- After created Job you can see in this panel.see image...
 Step 7:- Now you can see in jobs menu your job has been created and ready to start,after that you can start your job.see image.......


Step 8:- After click on "Start job at step" your job is running and performing according your query.see image.... 
Also you can check status of job in this panel.
Step 9:- After job completion you can see the "success" status for this job,see image....
 After that you can check your back file (.BAK) file has been created on specified path.
 Step 10:- After job completion you can see the history of job.see image..
After that you can see whole information and history of your job.see image..
Bikesh Srivastava SQL
Thursday, July 7, 2016

What is MERGE Query in SQL ?

Today i am clarify about how to Inserting, Updating, and Deleting Data by Using MERGE. In SQL Server 2008, you can perform insert, update, or delete operations in a single statement using the MERGE statement in SQL database.

Why we use MERGE statement in SQL?
In a typical data warehousing application, regularly amid the ETL cycle you have to perform INSERT, UPDATE and DELETE operations on a TARGET table by coordinating the records from the SOURCE table. For instance, an items measurement table has data about the items; you have to match up this table with the most recent data about the items from the source table. You would need to compose separate INSERT, UPDATE and DELETE proclamations to revive the objective table with an overhauled item list or do lookups. In spite of the fact that it is by all accounts straight forward at first look, yet it gets to be unwieldy when you have do it all the time or on different tables, even the execution debases fundamentally with this methodology. In this tip we will stroll through how to utilize the MERGE explanation and do this in one pass.


In SQL 2008 you can perform insert, update, or delete operations in a single statement using the MERGE statement . The MERGE statement allows you to join a data source table  with a target table or view, and then perform multiple actions against the target based on the results of that join. For example, you can use the MERGE statement to perform the given operations below.

Operation can perform using MERGE:-
1.According condition  insert,update,delete row in target table.If the row exists in the target table, update one or more columns; otherwise, insert the data into a new row.
2.Synchronize two tables.Insert, update, or delete rows in a target table based on differences with the source table .

Clauses(keyword) using  in MERGE Query.

1.MERGE -
The MERGE clause(keyword) specifies the table or view that is the target of the insert, update, or delete operations.
2.USING -
The USING clause(keywordspecifies the data source table being joined with the target table.
3.ON -
The ON clause(keywordspecifies the join conditions that determine where the target table and source table  match.
4.WHEN -
The WHEN clause(keyword(WHEN MATCHED, WHEN NOT MATCHED BY TARGET, and WHEN NOT MATCHED BY SOURCE) specify the actions to take based on the results of the ON clause(keywordand any additional search criteria specified in the WHEN clauses.
5.OUTPUT -
The OUTPUT clause(keywordreturns a row for each row in the target table  that is inserted, updated, or deleted.

Syntax for MERGE Query:-
MERGE [AS TARGET] 
USING [AS SOURCE] 
ON 
[WHEN MATCHED 
THEN ] 
[WHEN NOT MATCHED [BY TARGET] 
THEN ] 
[WHEN NOT MATCHED BY SOURCE 
THEN ];
 Simple Example with Query:-

Step 1:-Create two table source and target table and insert data .
 --Create a target table   
 CREATE TABLE Products ( ProductID INT PRIMARY KEY, ProductName VARCHAR(100), Rate MONEY )   
 GO   
 --Insert records into target table   
 INSERT INTO Products VALUES (1, 'Tea', 10.00), (2, 'Coffee', 20.00), (3, 'Muffin', 30.00), (4, 'Biscuit', 40.00)   
 GO   
 --Create source table   
 CREATE TABLE UpdatedProducts ( ProductID INT PRIMARY KEY, ProductName VARCHAR(100), Rate MONEY )   
 GO   
 --Insert records into source table   
 INSERT INTO UpdatedProducts VALUES (1, 'Tea', 10.00), (2, 'Coffee', 25.00), (3, 'Muffin', 35.00), (5, 'Pizza', 60.00)   
 GO   
 SELECT * FROM Products   
 SELECT * FROM UpdatedProducts   
 GO
Step 2:-Now i am going to use MERGE query to perform action on table:-
 --Synchronize the target table with
--refreshed data from source table
MERGE Products AS TARGETUSING UpdatedProducts AS SOURCE ON  

(TARGET.ProductID = SOURCE.ProductID) 

--When records are matched, update 
--the records if there is any change
WHEN MATCHED AND TARGET.ProductName <> SOURCE.ProductName 

 OR TARGET.Rate <> SOURCE.Rate

 THEN 

UPDATE SET TARGET.ProductName = SOURCE.ProductName, TARGET.Rate = SOURCE.Rate 

--When no records are matched, insert
--the incoming records from source
--table to target table
WHEN NOT MATCHED BY TARGET THEN INSERT (ProductID, ProductName, Rate) VALUES  

(SOURCE.ProductID, SOURCE.ProductName, SOURCE.Rate)

--When there is a row that exists in target table and
--same record does not exist in source table
--then delete this record from target table
WHEN NOT MATCHED BY SOURCE THEN DELETE


--$action specifies a column of type nvarchar(10) 
--in the OUTPUT clause that returns one of three 
--values for each row: 'INSERT', 'UPDATE', or 'DELETE', 
--according to the action that was performed on that row
OUTPUT $action, DELETED.ProductID AS TargetProductID, DELETED.ProductName AS  

TargetProductName, DELETED.Rate AS TargetRate, INSERTED.ProductID AS SourceProductID,

 INSERTED.ProductName AS SourceProductName, INSERTED.Rate AS SourceRate;  

SELECT @@ROWCOUNT; 
GO
Step 3:-Run script. After this script output is showing below in image.  There were 2 updates, 1 delete and 1 insert in target table.
Merged Example
If we select all records from the Products(target) table we can see the final results.  We can see the Coffee rate was updated from 20.00 to 25.00 in target table , the Muffin rate was updated from 30.00 to 35.00 in target table, Biscuit was deleted and Pizza was inserted inside target table.Result is showing like this.
Merged output
Description :-
The MERGE SQL statement requires a semicolon (;) as a statement terminator in SQL server database . Otherwise Error 10713 is raised when a MERGE statement is executed without the statement terminator  SQL server database.
  • Whenever you  used after MERGE, @@ROWCOUNT returns the total number of rows inserted, updated, and deleted to the client in SQL server database.
  • In SQL at least one of the three MATCHED clauses must be specified when using MERGE statement; the MATCHED clauses can be specified in any order. However a variable cannot be updated more than once in the same MATCHED clause.
  • Of course it's obvious, but just to mention, the person executing the MERGE statement should have SELECT Permission on the SOURCE Table and INSERT, UPDATE and DELETE Permission on the TARGET Table.
  • MERGE SQL statement improves the performance as all the data is read and processed only once whereas in previous versions three different statements have to be written to process three different activities (INSERT, UPDATE or DELETE) in which case the data in both the source and target tables are evaluated and processed multiple times; at least once for each statement.
  • MERGE SQL statement takes same kind of locks minus one Intent Shared (IS) Lock that was due to the select statement in the ‘IF EXISTS' as we did in previous version of SQL Server.
  • For every insert, update, or delete action specified in the MERGE statement, SQL Server fires any corresponding AFTER triggers defined on the target table, but does not guarantee on which action to fire triggers first or last. Triggers defined for the same action honor the order you specify.
Bikesh Srivastava SQL

Life Is Complicated, But Now programmer Can Keep It Simple.