Tuesday, 18 July 2017

What are the difference between DDL, DML , DCL and TCL commands?

Database Command Types

Data Definition Language (DDL) statements are used to define the database structure or schema. 
-          CREATE - to create objects in the database
-          ALTER - alters the structure of the database
-          DROP - delete objects from the database
-          TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
-          COMMENT - add comments to the data dictionary
-          RENAME - rename an object

Data Manipulation Language (DML) statements are used for managing data in database. DML commands are not auto-committed. It means changes made by DML command are not permanent to database, it can be rolled back.
-          SELECT – retrieve data from the a database
-          INSERT – insert data into a table
-          UPDATE – updates existing data within a table
-          DELETE – deletes all records from a table, the space for the records remain
-          MERGE – UPSERT operation (insert or update)
-          CALL – call a PL/SQL or Java subprogram
-          LOCK TABLE – control concurrency

Data Control Language (DCL) statements. Some examples:
-          GRANT - gives user's access privileges to database
-          REVOKE - withdraw access privileges given with the GRANT command


Transaction Control Language (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.

-          COMMIT - save work done
-          SAVEPOINT - identify a point in a transaction to which you can later roll back
-          ROLLBACK - restore database to original since the last COMMIT
-     SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use

Saturday, 15 July 2017

Create SQL Server Job in Easy Steps

Job is a set of one or more management tasks. The SQL Server Agent service is managing SQL server jobs. SQL Server Agent is a windows service.
This topic will help to beginners to create SQL Server Jobs in a easy steps. Install Sql Server Management Studio and Go SQL Server Agent.

Some time customer want to complete a specific action in periodically like “Daily”, “Weekly”, and “Monthly”.

  • DBA can Backup database
  • Log repor
  • Data Synchronization (bad practice).
  • Monitoring 

For this tutorial, have created a store procedure that basically calculate “Total Sales Amount”, “Total Discount Amount”, “Total Product” for daily sales and insert this record into a table. For beginners, using “Northwind” database download from codeplex or Microsoft

Create table DailySalesRecords to hold date wise total sale records.


CREATE TABLE [dbo].[DailySalesRecords](
      [OrderDate] [datetime] NOT NULL,
      [TotalAmount] [decimal](18, 4) NOT NULL,

      [TotalDiscount] [decimal](18, 4) NOT NULL,
      [TotalProducts] [bigint] NOT NULL,
      [JobExecutionTime] [datetime] NOT NULL


-- =============================================
-- Author:http://www.code-lake.blogspot.com/
-- Create date: 14-July
-- Description: Get datewise total sales 
-- EXEC DailyTotalSales  
-- =============================================
CREATE PROCEDURE [dbo].[DailyTotalSales] 
 -- SET NOCOUNT ON added to prevent extra result sets from
 INSERT INTO DailySalesRecords 
 SELECT O.OrderDate, SUM( (OD.Quantity * OD.UnitPrice)) AS TotalAmount
  ,SUM(OD.Discount)AS TotalDiscount,SUM(OD.Quantity) AS TotalProduct, GETDATE()
  Orders O INNER JOIN 
  [Order Details] AS OD ON O.OrderID = OD.OrderID
  WHERE Convert (varchar(10),O.OrderDate,110)= Convert (varchar(10), GETDATE()-1,110)
  GROUP By O.OrderDate 

 1. Right clicks on Jobs and click New Job…


      2.Give a proper job name, add job owner generally owner will be DBA. Select job category   optional. Category simply helps DBA to monitor jobs. We can create category and assign jobs to new category.


    3. Click Steps => Click New to open Job Step Properties wizard. Give step name like “Step1-DailyExecute” => Select type “Transact-SQL script (T-SQL) => Select database where execute command script. In command area, we can add select statement, execute store procedure. We can add more steps.

   4.In advanced area, we can set next action after “On success action” and “On failure action”. Add no of “Retry attempts” when fail. Create a output file in your safe drive, in every action system will write log in output file


    5. Add New Schedule. Select Schedule = > click new. Give Schedule name, select  schedule type, select frequency daily, weekly or monthly in different recurs. We can    set start time and also end time. 


      6. We can set alert. For alert, give alert name = > checked enable => select type =>               Select you database = > Select Severity. Any kind of exception from alert can be sent to         email, pager, network 

        7. we can sent confirmation in E-mail, Page, net send and also write OS event log when j      job  succeeds , completes or fails 

   To complete this clicks Ok. We can create job with a single script.

USE [msdb]

SELECT @ReturnCode = 0

-- if Exist in same name
IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback


EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'Job_DailySales', --add job name
  @description=N'Daily total ordder calculaion, amount, discount', 
  @category_name=N'[Uncategorized (Local)]', 
  @owner_login_name=N'sa', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/****** Object:  Step [Step1-DailExecute]    Script Date: 07/15/2017 21:40:15 ******/
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Step1-DailExecute',
  @os_run_priority=0, @subsystem=N'TSQL', 
  @output_file_name=N'E:\Working Project\Documents\Code-Lake.Blogspot.com\Sql Server job\DailySalesLog', 
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'DailySalesRecords', 
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
GOTO EndSave


If have any query please leave a comments.