Tuesday, 18 July 2017

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

Database Command Types

DDL
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

DML
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

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

TCL

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.

Purpose:
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.



USE [NORTHWIND]
GO

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
) ON [PRIMARY]

GO



-- =============================================
-- Author:http://www.code-lake.blogspot.com/
-- Create date: 14-July
-- Description: Get datewise total sales 
-- EXEC DailyTotalSales  
-- =============================================
CREATE PROCEDURE [dbo].[DailyTotalSales] 
AS
BEGIN
 -- SET NOCOUNT ON added to prevent extra result sets from
 SET NOCOUNT ON;
 
 
 INSERT INTO DailySalesRecords 
 
 SELECT O.OrderDate, SUM( (OD.Quantity * OD.UnitPrice)) AS TotalAmount
  ,SUM(OD.Discount)AS TotalDiscount,SUM(OD.Quantity) AS TotalProduct, GETDATE()
 FROM 
  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 
END


    
 1. Right clicks on Jobs and click New Job…


General:

      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.




Step:    

    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




Schedule:

    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. 



    
       Alert:


      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 



       
         
        Notification:
     
        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]
GO

BEGIN TRANSACTION
DECLARE @ReturnCode INT
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)
BEGIN
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

END

DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'Job_DailySales', --add job name
  @enabled=1, 
  @notify_level_eventlog=0, 
  @notify_level_email=0, 
  @notify_level_netsend=0, 
  @notify_level_page=0, 
  @delete_level=0, 
  @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',
  @step_id=1, 
  @cmdexec_success_code=0, 
  @on_success_action=1, 
  @on_success_step_id=0, 
  @on_fail_action=2, 
  @on_fail_step_id=0, 
  @retry_attempts=3, 
  @retry_interval=10, 
  @os_run_priority=0, @subsystem=N'TSQL', 
  @database_name=N'NORTHWIND.MDF', 
  @output_file_name=N'E:\Working Project\Documents\Code-Lake.Blogspot.com\Sql Server job\DailySalesLog', 
  @flags=2
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', 
  @enabled=1, 
  @freq_type=4, 
  @freq_interval=1, 
  @freq_subday_type=1, 
  @freq_subday_interval=0, 
  @freq_relative_interval=0, 
  @freq_recurrence_factor=0, 
  @active_start_date=20170714, 
  @active_end_date=20170714, 
  @active_start_time=1000, 
  @active_end_time=235959, 
  @schedule_uid=N'cbdf1f2b-c6a9-4d3a-bb75-39ab3c1c781b'
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
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:

GO

If have any query please leave a comments.