Wednesday, September 30, 2015

Creating copy of existing SQL Server for development or testing purpose

Installation :
Install .NET frame work 3.5
Install SQL Server 2012
Applied latest Service pack 2(Restart)
Copy-Restore the databases from  server X to Server Y 
Changed  all databases compatibility to 110


DB mail:
Configure Database Mail, SQL Operator, Configure Mail profiles to SQL Agent , Restart SQL Agent


Logins/Users:
Create necessary logins,users and check if any orphan users 
sa with strong password 


Jobs:
Created Backup Jobs to run Daily 11am(purge backups older than 2 days)
Rebuild indexes   
Update Statistics 
Created Space alert Job 


Linked Servers:
create if needed any 

.net Framework 3.5 (NetFx3 ) error while installing SQL Server 2012

TITLE: Microsoft SQL Server 2012 Service Pack 1 Setup
------------------------------

The following error has occurred:

Error while enabling Windows feature : NetFx3, Error Code : -2146498298 , Please try enabling Windows feature : NetFx3 from Windows management tools and then run setup again. For more information on how to enable Windows features ,
see http://go.microsoft.com/fwlink/?linkid=227143

For help, click: http://go.microsoft.com/fwlink?LinkID=20476&ProdName=Microsoft%20SQL%20Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=11.0.3000.0&EvtType=0x681D636F%25401428%25401

------------------------------
BUTTONS:

OK
------------------------------


Resolution:
Install net Framework 3.5 Features
NOTE: should have the OS CD mounted to CD ROM 

Server Manager -->Add Roles and Features-->Role -based-->.net Framework..
http://sqlblog.com/blogs/sergio_govoni/archive/2013/07/13/how-to-install-netfx3-on-windows-server-2012-required-by-sql-server-2012.aspx

Tuesday, September 29, 2015

Restore from database snapshot drops FULLTEXT CATALOGS

I am working with Automation team and for the sake of testing i have created the snapshot, the database contains FULL TEXT Catalogs...

so, when i have restored the Snapshots to database  i have lost all FULL TEXT catalogs..

FYI.. must backup of Full text CATALOGS before taking any snapshot backups or restores

fyi...https://technet.microsoft.com/en-us/library/ms179557(v=sql.105).aspx

Advantages of using snapshots:
http://blog.sqlauthority.com/2008/09/05/sql-server-creating-full-text-catalog-and-index/

Monday, September 28, 2015

Managing jobs in always on Availability groups

I have Setup Always on Availability Groups between 2 servers and i have a Script that i wanted to put in Job and i want to run the job only on primary at any time..(one active and one secondary)

USE MASTER
GO
DECLARE @ServerName NVARCHAR(256)  = @@SERVERNAME
DECLARE @RoleDesc NVARCHAR(60)

SELECT @RoleDesc = a.role_desc
    FROM sys.dm_hadr_availability_replica_states AS a
    JOIN sys.availability_replicas AS b
        ON b.replica_id = a.replica_id
WHERE b.replica_server_name = @ServerName

IF @RoleDesc = 'PRIMARY'



BEGIN
USE TestAG
Insert into CheckAvailabilityRoleJobs(InsertDate,ServerName,RoleDescription)
SELECT GETDATE(),@@SERVERNAME, a.role_desc
FROM      sys.dm_hadr_availability_replica_states AS a
JOIN sys.availability_replicas AS b ON b.replica_id = a.replica_id
where   b.replica_server_name=@@SERVERNAME
END


ELSE

BEGIN

      RETURN  
END 
I wanted to keep this job running 24X7 on both servers, but insert happens only on Primary at any time , in secondary the JOB exits with out actually inserting...
the script  is running good on PRIMARY, but when i try to run on SECONDARY it is failing ...
the script should actually exit on SECONDARY after checking Primary or not but it is trying too connect TESTAG database which is not accessible on secondary
Msg 976, Level 14, State 1, Line 16
The target database, 'TestAG', is participating in an availability group and is currently not accessible for queries. Either data movement is suspended or the availability replica is not enabled for read access. To allow read-only access to this and other databases in the availability group, enable read access to one or more secondary availability replicas in the group.  For more information, see the ALTER AVAILABILITY GROUP statement in SQL Server Books Online.

Answer:
I found out that ...secondary server should be Readable ..it is not possible to run jobs/check in secondary servers  which are not readable 

Failover or Restart Results in Reseed of Identity – FIX ALWAYS ON Availability Groups

I did set up always on between 2 servers 1 active 1 passive(readable not writable)
i had  a table with identity, when failover happens and i try to insert the data , the identity went from current row to 1000, i was surprised and the with little bit of research i found a way to solve the issue...

WHEN EVER SQL restart happens or Failover happens which means a Role is changed , so when a role is changed we need to have a mechanism to notify

1. Configure role with error number =1480
and then in response execute a sql job ,and notify Operator

SQL JOB Code below: on both servers..

USE MASTER
GO

DECLARE @ServerName NVARCHAR(256)  = @@SERVERNAME
DECLARE @RoleDesc NVARCHAR(60)


SELECT @RoleDesc = a.role_desc
    FROM sys.dm_hadr_availability_replica_states AS a
    JOIN sys.availability_replicas AS b
        ON b.replica_id = a.replica_id
WHERE b.replica_server_name = @ServerName

IF @RoleDesc = 'PRIMARY'



BEGIN
USE MASTER
EXEC [dbo].[sp_FixIdentityReSeeds]
END


ELSE

BEGIN

      RETURN  
END




------------The sp is below


USE [master]
GO
/****** Object:  StoredProcedure [dbo].[sp_FixIdentityReSeeds]    Script Date: 10/8/2015 2:24:08 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_FixIdentityReSeeds]
AS
BEGIN

    --foreach database
    DECLARE @DatabaseName varchar(255)

    DECLARE DatabasesCursor CURSOR READ_ONLY
    FOR
        SELECT name
        FROM sys.databases
        where name not in ('master','tempdb','model','msdb') and
        sys.databases.state_desc = 'online'

    OPEN DatabasesCursor

    FETCH NEXT FROM DatabasesCursor
    INTO @DatabaseName

    WHILE @@FETCH_STATUS = 0
    BEGIN

        EXEC ('USE '+@DatabaseName + '

        --foreach identity column
        DECLARE @tableName varchar(255)
        DECLARE @columnName varchar(255)
        DECLARE @schemaName varchar(255)

        DECLARE IdentityColumnCursor CURSOR READ_ONLY
        FOR

            select TABLE_NAME , COLUMN_NAME, TABLE_SCHEMA
            from INFORMATION_SCHEMA.COLUMNS
            where COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME,
                                 ''IsIdentity'') = 1 and TABLE_NAME not like ''%syncobj_0x%''

        OPEN IdentityColumnCursor

        FETCH NEXT FROM IdentityColumnCursor
        INTO @tableName, @columnName, @schemaName

        WHILE @@FETCH_STATUS = 0
        BEGIN

            print ''['+@DatabaseName+'].[''+@tableName+''].[''+
                            @schemaName+''].[''+@columnName+'']''
            EXEC (''declare @MAX int = 0
                    select @MAX = max(''+@columnName+'')
                    from ['+@DatabaseName+'].[''+@schemaName+''].[''+@tableName+'']
                    if (@MAX IS NULL)
                    BEGIN
                        SET @MAX = 0
                    END
                    DBCC CHECKIDENT(['+@DatabaseName+'.''+
                                    @schemaName+''.''+@tableName+''],RESEED,@MAX)'')

            FETCH NEXT FROM IdentityColumnCursor
            INTO @tableName, @columnName, @schemaName

        END

        CLOSE IdentityColumnCursor
        DEALLOCATE IdentityColumnCursor')

        FETCH NEXT FROM DatabasesCursor
        INTO @DatabaseName

    END

    CLOSE DatabasesCursor
    DEALLOCATE DatabasesCursor
END




EXEC sp_configure 'show advanced options', 1 ;

Friday, September 25, 2015

Create a Database snapshot, Restore from snapshot, Delete the snapshot files

 use Test
go
declare
@Number INT,
@ssdirname varchar(1000),
@targetdb varchar(255),
@Drop Varchar(max)

Set @Number=1
SET @ssdirname = 'D:\DatabaseSnapshots\'
SET @targetdb = DB_NAME() +'Snapshot'+ Convert(Varchar(10),@Number)

---SET @targetdb = DB_NAME() +'Snapshot'+ Convert(Varchar(10),@Number)+Convert(Varchar(100),getdate(),112)

--print @targetDb


-- Unique timestamp for filenames
DECLARE @timestamp varchar(50)
SET @timestamp = REPLACE(REPLACE(REPLACE(CONVERT(varchar(50),GETDATE(),126),':',''),'.',''),'-','')

DECLARE oncmd CURSOR FOR
select OnCmd = '(NAME=''' + [name] + ''', FILENAME=''' + @ssdirname + [name]  + @timestamp + '.ss'')'
from sys.database_files
where [type] = 0

DECLARE @oncmd varchar(500), @sqlcmd varchar(4000)
SET @sqlcmd = ''

OPEN oncmd
FETCH NEXT FROM oncmd INTO @oncmd
WHILE @@FETCH_STATUS = 0
BEGIN
IF @sqlcmd <> ''
SET @sqlcmd = @sqlcmd + ', ' + CHAR(10)
SET @sqlcmd = @sqlcmd + @oncmd

FETCH NEXT FROM oncmd INTO @oncmd
END
CLOSE oncmd
DEALLOCATE oncmd

SET @sqlcmd = 'CREATE DATABASE ' + @targetdb + ' ON ' + CHAR(10) + @sqlcmd
SET @sqlcmd = @sqlcmd + CHAR(10) + 'AS SNAPSHOT OF ' + DB_NAME()

------------------------------------------------------------------------------------
--STEP1:CREATE Database snapshot
IF EXISTS(select * from sys.databases where name='dbname')
DROP DATABASE dbname

--EXEC (@sqlcmd)
PRINT @SQlCMD
PRINT 'PUT YOUR CODE HERE '--TEST COMPLETE/Automation --- go to step 2


--ALTER DATABASE Test
-- SET SINGLE_USER WITH ROLLBACK IMMEDIATE
--GO

--ALTER DATABASE test
-- SET MULTI_USER
--GO


--STEP2:
---Restore File

 Declare @RestoreCmd Varchar(max)
SET @RestoreCmd= 'RESTORE DATABASE Test FROM DATABASE_SNAPSHOT='''+  @targetdb    +  ''''
--EXEC (@sqlcmd)
print @RestoreCmd



USE MASTER
GO
/****** Object:  StoredProcedure [dbo].[SPRestoreSnapshot]    Script Date: 9/28/2015 5:21:04 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTEr PROCEDURE [dbo].[SPRestoreSnapshot]
AS

ALTER DATABASE dbname
SET SINGLE_USER WITH ROLLBACK IMMEDIATE


    DECLARE @Number INT ,
        @ssdirname VARCHAR(1000) ,
        @targetdb VARCHAR(255) ,
        @Drop VARCHAR(MAX);


    SET @Number = 1;
    SET @ssdirname = 'D:\DatabaseSnapshots\';
    SET @targetdb = 'dbname' + 'Snapshot' + CONVERT(VARCHAR(10), @Number);


    DECLARE @RestoreCmd VARCHAR(MAX);
    SET @RestoreCmd = '
USE MASTER

    RESTORE DATABASE dbname FROM DATABASE_SNAPSHOT='''
        + @targetdb + '''';
    EXEC (@RestoreCmd)
ALTER DATABASE DB
SET MULTI_USER
;
--print (@RestoreCmd)








 PRINT 'WANTS TO delete, insert ,DROP '--GO TO STEP3


 --STEP3:
--DELETE THE Database SnapShot and the FILES associated with snapshot in the Folder
SET @DROP = 'DROP DATABASE ' + @targetdb + ';' + CHAR(10)
--EXEC (@DROP)
PRINT @DROP

Thursday, September 24, 2015

Create Snapshot of databases





USE master;
GO
CREATE DATABASE TestDB;
GO
USE TestDB;
GO
CREATE TABLE Test
    (
      id INT ,
      Name VARCHAR(10) NULL
    );

INSERT  INTO Test
VALUES  ( 1, 'Naresh' ),
        ( 2, 'Kumar' ),
        ( 3, 'Koudagani' );


CREATE DATABASE TestDB_Snapshot ON
( NAME = TestDB, FILENAME = 'C:\MSSQL\Data\myDb_snapshot.ss' )
AS SNAPSHOT OF TestDB;

select file_id, name, type_desc from sys.database_files
delete from test
select * from test

SELECT * from TestDB_Snapshot.dbo.test
RESTORE DATABASE TestDB FROM DATABASE_SNAPSHOT ='TestDB_Snapshot'
go
select * from TestDB.dbo.Test

Monday, September 21, 2015

SQL Server Configuration Manager

How to open sql server configuration manager in Windows Server 2012 or 2012 R2 ?

1. RUN--type 
SQLServerManager12.msc  for sql server 2014 
SQLServerManager10.msc  for sql server 2008


2. From Search options type above as required 



Because SQL Server Configuration Manager is a snap-in for the Microsoft Management Console program and not a stand-alone program, SQL Server Configuration Manager not does not appear as an application when running Windows 8. To open SQL Server Configuration Manager, in the Search charm, under Apps, type SQLServerManager12.msc for SQL Server 2014 (SQLServerManager11.msc for SQL Server 2012 or SQLServerManager10.msc for SQL Server 2008), and then press Enter.

Thursday, September 17, 2015

HOW to Find Unused databases


Step1:
---Create a table to keep track of connectios:
USE AuditDB;
GO
CREATE TABLE [dbo].[TrackDBConnections]
    (
      ServerName VARCHAR(50) NOT NULL ,
      DatabaseName VARCHAR(30) NOT NULL ,
      NumberOfConnections INT NOT NULL ,
      LoginTime DATETIME NOT NULL ,
      LastBatch DATETIME NOT NULL ,
      DateTimeRecordInsertd DATETIME NULL ,
      Status VARCHAR(100) NULL ,
      HostName VARCHAR(100) NULL ,
      ProgramName VARCHAR(1000) NULL ,
      NTusername VARCHAR(100) NULL ,
      Loginame VARCHAR(100) NULL
    )
ON  [PRIMARY];
GO





Step2:--Main Step
---create a SP to insert the Data into the [TrackDBConnections] Table:
USE AuditDB
GO
CREATE PROCEDURE usp_TrackDBConnections
AS
BEGIN

 /*    The main purpose of the SP is to keep track of Connections which get connect to Databases
                and decide on which database is being used or not being used by any applications and then make OFFLINE for fewdays, backup and then drop..
 */


 SET NOCOUNT ON;
INSERT INTO [TrackDBConnections](ServerName, DatabaseName,LoginTime,LastBatch,DateTimeRecordInsertd,NumberOfConnections,Status,HostName,ProgramName,NTusername,Loginame)
 
  SELECT  @@ServerName AS SERVER ,
        name ,
        login_time ,
        last_batch ,
        GETDATE() AS DATE ,
        COUNT(status) AS number_of_connections ,
        status ,
        hostname ,
        program_name ,
        nt_username ,
        loginame
FROM    sys.databases d
        LEFT JOIN sysprocesses sp ON d.database_id = sp.dbid
WHERE   database_id NOT BETWEEN 0 AND 4
        AND loginame IS NOT NULL
GROUP BY name,status,login_time ,
        last_batch,hostname ,
        program_name ,
        nt_username ,
        loginame;

END


--Step3:-Create a Job to schedule to run every 10 Minutes
       --Let it run for Few days/1 week and see the results with below query,Detailed SQL Server Connection Information



--Step4: CHECK results
----count
SELECT  DatabaseName ,
COUNT(status) AS number_of_connections,
ProgramName
FROM    TrackDBConnections
 GROUP BY DatabaseName,ProgramName,Status
 GO

--Details
 SELECT *  from TrackDBConnections
GO

 
   

How licensing works with AlwaysOn Availability groups

I would like to share some knowledge on how licensing works with AlwaysOn Availability groups.
It took 1 week to figure it out, Having calls with Microsoft and help from forums


Min Requirements for having AlwaysOn Availability groups.:

  • Two Windows Servers 2012 R2 Standard Edition
  • Ensure that each computer is a Node in a Windows Server Fail over Clustering (WSFC)
  • All two Windows Servers should reside on one Cluster and One Domain
  • Each SQL Server Instance involved in AlwaysOn Availability Groups must be running Enterprise Edition of SQL Server 2012 or later (2014)
  • Must use same network links for communications between WSFC members and availability Replicas
  • All Databases should be in Full recovery model, only User databases can participate in AlwaysOn Availability Groups 
  • Recommended to keep all configurations/Settings/Drives identical between two nodes


Advantages of using AlwaysOn Availability Groups:
  • AlwaysOn Availability Groups build on Top of Windows Server Fail over Clustering (WSFC)
  • Automatics Failover(Synchronous mode), No witness server needed for automatic failover, uses Windows Server Failover Clustering to do Automatic Failover
  • Can have multiple copies of secondary, but here at FrontPoint we are not going to use secondary
  • Backups and DBCC Check DB operations cane be done on secondary( but need to pay for License)
  • Applications connect to Virtual Server Name any given time, and we do not need to change any in connection strings even after Failover happens 
  • Secondary Replica can be same or different location 
  • More than one secondary and cane be readable and run synchronous mode 
  • Multiple database failover -AlwaysOn Availability Groups ensures all databases are connected when failover happen to secondary Replica
  • No shared Storage is required in AlwaysOn Availability Groups 
AlwaysOn Availability Groups Support Fail over In any of the following  Events
  • Operating System goes down
  • SQL Server Instance, Database goes offline/Shutdown
  • Disk Failures(hardware failures) in which databases cannot be accessed 
  • Network goes down or someone unplug Network cables
  • Manual failover whenever needed in emergency situations
  • Upgrade/Patch Failed/Restarting SQL services 

Manage Jobs and Replication:
  • Jobs should be created on both primary and secondary Replicas with some logic.
  • Jobs run on both servers all times, but which ever is primary actually execute the job and secondary will not pass validation Skip the job to execute the actual code
  • Replication Jobs will be Created on Both server and have to create publications on both servers and configure Distribution database to use remote distributor
IF ( SELECT ars.role_desc
 FROM   sys.dm_hadr_availability_replica_states ars
           INNER JOIN sys.availability_groups ag ON ars.group_id = ag.group_id
         WHERE  ag.name = 'YourAvailabilityGroupName'
         AND ars.is_local = 1
   ) = 'PRIMARY‘
BEGIN
---this server is the primary replica, Put all Job code here 
 END;
ELSE
BEGIN
PRINT 'no';    -- this server is not the primary replica, (optional) do something here
    END;


Finally, How licensing works with AlwaysOn Availability groups ?

 
I am going to explain how it works when we have like below environment

SQL Server 2014 Always ON Availability Groups between 2 nodes(servers) and using SQL server Enterprise edition on top of WSFC, Node1 is primary replica(read/Write)  and Node2 is secondary replica(NON READABLE)  and databases are Restoring mode only and will not use or read/write  data until disaster (failover)happens.

As per documentation , SQL server  Services, Agent  services should run on both servers at anytime but only Primary Replica's  jobs executes at anytime using Some checks like i provided above t SQL script, so we should have JOBS running at both servers, we will have to put a logic inside the jobs , if this is primary execute else come out of the job..--this code or logic make sure the jobs run on PRIMARY REPLICA (now, or after failover)

so we need only 1 SQL SERVER ENTERPRISE Licence to setup ENVIRONMENT like above.....

Note:

1.You probably shouldn't take my word for it, since I don't work for Microsoft, but I'm pretty sure that isn't a problem, You need to have the server ready to take over for any failure. Having your jobs already configured and scheduled is an important part of that.

2.Passive fail-over rights permit a customer to run passive instances of SQL Server in a separate operating system environment (OSE) without requiring the passive server to be licensed for SQL Server. A passive SQL Server instance is one that is not serving SQL Server data to clients or running active SQL Server workloads.e over for any failure. Having your jobs already configured and scheduled is an important part of that.


Some Useful Information:
For each server licensed with SQL Server 2014 and covered by active SA, customers can run up to the same number of passive failover instances in a separate, on-premises OSE to support failover events.
A passive SQL Server instance is one that is not serving SQL Server data to clients or running active SQL Server workloads. The passive failover instances can run on a separate server. These may only be used to synchronize with the primary server and otherwise maintain the passive database instance in a warm standby state in order to minimize downtime due to hardware or software failure.

The secondary server used for failover support does not need to be separately licensed for SQL Server as long as it is truly passive, and the primary SQL Server is covered with active SA. If it is serving data, such as reports to clients running active SQL Server workloads, or performing any “work”, such as additional backups being made from secondary servers, then it must be licensed for SQL Server. 

http://download.microsoft.com/download/B/4/E/B4E604D9-9D38-4BBA-A927-56E4C872E41C/SQL_Server_2014_Licensing_Guide.pdf

So long as the agent jobs only actually perform "work" on the primary, and the other conditions are met, it would be passive. 



Thanks
Naresh DBA



















Tuesday, September 15, 2015

Difference between NORecovery vs STANDBY

 
RECOVERY is the normal and usual status of the database where users can connect and access the database (given that they have the proper permissions set up).



NORECOVERY allows the Database Administrator to restore additional backup files such as Differential or Transactional backups. While the database is in this state then users are not able to connect or access this database.



STANDBY is pretty much the same as NORECOVERY status however it allows users to connect or access database in a READONLY access. So the users are able to run only SELECT command against the database. This is used in Log Shipping quite often for reporting purposes. The only drawback is that while there are users in the database running queries SQL Server or a DBA is not able to restore additional backup files. Therefore if you have many users accessing the database all the time then the replication could fall behind.

Thursday, September 10, 2015

SQL Server Find What Jobs Are Running a Procedure


SELECT j.name
  FROM msdb.dbo.sysjobs AS j
  WHERE EXISTS
  (
    SELECT 1 FROM msdb.dbo.sysjobsteps AS s
      WHERE s.job_id = j.job_id
      AND s.command LIKE '%SPNAME%'
  );

or to get more details:
SELECT
    [sJOB].[job_id] AS [JobID]
    , [sJOB].[name] AS [JobName]
    , [sJSTP].[step_uid] AS [StepID]
    , [sJSTP].[step_id] AS [StepNo]
    , [sJSTP].[step_name] AS [StepName]
    , CASE [sJSTP].[subsystem]
        WHEN 'ActiveScripting' THEN 'ActiveX Script'
        WHEN 'CmdExec' THEN 'Operating system (CmdExec)'
        WHEN 'PowerShell' THEN 'PowerShell'
        WHEN 'Distribution' THEN 'Replication Distributor'
        WHEN 'Merge' THEN 'Replication Merge'
        WHEN 'QueueReader' THEN 'Replication Queue Reader'
        WHEN 'Snapshot' THEN 'Replication Snapshot'
        WHEN 'LogReader' THEN 'Replication Transaction-Log Reader'
        WHEN 'ANALYSISCOMMAND' THEN 'SQL Server Analysis Services Command'
        WHEN 'ANALYSISQUERY' THEN 'SQL Server Analysis Services Query'
        WHEN 'SSIS' THEN 'SQL Server Integration Services Package'
        WHEN 'TSQL' THEN 'Transact-SQL script (T-SQL)'
        ELSE sJSTP.subsystem
      END AS [StepType]
    , [sPROX].[name] AS [RunAs]
    , [sJSTP].[database_name] AS [Database]
    , [sJSTP].[command] AS [ExecutableCommand]
    , CASE [sJSTP].[on_success_action]
        WHEN 1 THEN 'Quit the job reporting success'
        WHEN 2 THEN 'Quit the job reporting failure'
        WHEN 3 THEN 'Go to the next step'
        WHEN 4 THEN 'Go to Step: '
                    + QUOTENAME(CAST([sJSTP].[on_success_step_id] AS VARCHAR(3)))
                    + ' '
                    + [sOSSTP].[step_name]
      END AS [OnSuccessAction]
    , [sJSTP].[retry_attempts] AS [RetryAttempts]
    , [sJSTP].[retry_interval] AS [RetryInterval (Minutes)]
    , CASE [sJSTP].[on_fail_action]
        WHEN 1 THEN 'Quit the job reporting success'
        WHEN 2 THEN 'Quit the job reporting failure'
        WHEN 3 THEN 'Go to the next step'
        WHEN 4 THEN 'Go to Step: '
                    + QUOTENAME(CAST([sJSTP].[on_fail_step_id] AS VARCHAR(3)))
                    + ' '
                    + [sOFSTP].[step_name]
      END AS [OnFailureAction]
FROM
    [msdb].[dbo].[sysjobsteps] AS [sJSTP]
    INNER JOIN [msdb].[dbo].[sysjobs] AS [sJOB]
        ON [sJSTP].[job_id] = [sJOB].[job_id]
    LEFT JOIN [msdb].[dbo].[sysjobsteps] AS [sOSSTP]
        ON [sJSTP].[job_id] = [sOSSTP].[job_id]
        AND [sJSTP].[on_success_step_id] = [sOSSTP].[step_id]
    LEFT JOIN [msdb].[dbo].[sysjobsteps] AS [sOFSTP]
        ON [sJSTP].[job_id] = [sOFSTP].[job_id]
        AND [sJSTP].[on_fail_step_id] = [sOFSTP].[step_id]
    LEFT JOIN [msdb].[dbo].[sysproxies] AS [sPROX]
        ON [sJSTP].[proxy_id] = [sPROX].[proxy_id]
WHERE [sJSTP].[command] LIKE '%SPNAME%'
ORDER BY [JobName], [StepNo]

why Distribution on SQL Express Edition is not possible

SQL server Distribution which act as intermediate and ruin jobs cannot be on SQL Express edition as SQL Express edition cannot have SQL Agent.

decrypt Stored procedure

Create SP with encryption:
CREATE PROCEDURE Test
WITH ENCRYPTIONAS
SELECT TOP 
10 CityFROM Person.Address
GO



Now we cannot view the Definition of SP 



To view the definition of the view:I have downloaded below one and it worked excellent...

https://www.devart.com/dbforge/sql/sqldecryptor/download.html



Thanks to devart

Tuesday, September 8, 2015

Find if sql server uses SSL Certificate




You can use below scripts to find out if any sql server is using  SSL certificate 

SELECT session_id, encrypt_option,*
FROM sys.dm_exec_connections

select * from sys.dm_exec_connections where encrypt_option = 'TRUE'

Both above scripts let u find out if SSL certificate is used or not.
If yes, the get the session_ID and check which application is being used.


sp_wHO2'ACTIVE'

DBCC INPUTBUFFER(51)


https://blog.sqlauthority.com/2009/06/27/sql-server-fix-error-17892-logon-failed-for-login-due-to-trigger-execution-changed-database-context...