Tuesday, December 17, 2013

How to drop distribution database

I just tested Transactional Replication Today on  test server as we( our client)  are going to have replication on our two big Databases

 so ...


After setting up Replication and  wanted to remove  all replication jobs, databases.. Distribution Database wont get dropped . so us below script to drop the distribution database


use master
go
alter database distribution1 set offline;
drop database distribution1;

Tuesday, November 26, 2013

Find any sql job running

I use this below querey  to find any sql job running when i see performance problem

USE MSDB

SELECT name AS [Job Name]
         ,CONVERT(VARCHAR,DATEADD(S,(run_time/10000)*60*60 /* hours */
          +((run_time - (run_time/10000) * 10000)/100) * 60 /* mins */
          + (run_time - (run_time/100) * 100)  /* secs */
           ,CONVERT(DATETIME,RTRIM(run_date),113)),100) AS [Time Run]
         ,CASE WHEN enabled=1 THEN 'Enabled'
               ELSE 'Disabled'
          END [Job Status]
         ,CASE WHEN SJH.run_status=0 THEN 'Failed'
                     WHEN SJH.run_status=1 THEN 'Succeeded'
                     WHEN SJH.run_status=2 THEN 'Retry'
                     WHEN SJH.run_status=3 THEN 'Cancelled'
               ELSE 'Unknown'
          END [Job Outcome]
FROM   sysjobhistory SJH
JOIN   sysjobs SJ
ON     SJH.job_id=sj.job_id
WHERE  step_id=0
AND    DATEADD(S,
  (run_time/10000)*60*60 /* hours */
  +((run_time - (run_time/10000) * 10000)/100) * 60 /* mins */
  + (run_time - (run_time/100) * 100)  /* secs */,
  CONVERT(DATETIME,RTRIM(run_date),113)) >= DATEADD(d,-1,GetDate())
ORDER BY name,run_date,run_time 


IF OBJECT_ID('tempdb.dbo.#RunningJobs') IS NOT NULL
      DROP TABLE #RunningJobs
CREATE TABLE #RunningJobs ( 
Job_ID UNIQUEIDENTIFIER, 
Last_Run_Date INT, 
Last_Run_Time INT, 
Next_Run_Date INT, 
Next_Run_Time INT, 
Next_Run_Schedule_ID INT, 
Requested_To_Run INT, 
Request_Source INT, 
Request_Source_ID VARCHAR(100), 
Running INT, 
Current_Step INT, 
Current_Retry_Attempt INT, 
State INT )   
    
INSERT INTO #RunningJobs EXEC master.dbo.xp_sqlagent_enum_jobs 1,garbage 

SELECT   
  name AS [Job Name]
 ,CASE WHEN next_run_date=0 THEN '[Not scheduled]' ELSE
   CONVERT(VARCHAR,DATEADD(S,(next_run_time/10000)*60*60 /* hours */
  +((next_run_time - (next_run_time/10000) * 10000)/100) * 60 /* mins */
  + (next_run_time - (next_run_time/100) * 100)  /* secs */,
  CONVERT(DATETIME,RTRIM(next_run_date),112)),100) END AS [Start Time]
FROM     #RunningJobs JSR
JOIN     msdb.dbo.sysjobs
ON       JSR.Job_ID=sysjobs.job_id
WHERE    Running=1 -- i.e. still running
ORDER BY name,next_run_date,next_run_time

Orphan users fix

Attaching and restoring databases from one server instance to another are common tasks executed by a DBA. After attaching or restoring of a database, previously created and configured logins in that database do not provide access. The most common symptoms of this problem are that the application may face login failed errors or you may get a message like the user already exists in the current database when you try to add the login to the database. This is a common scenario when performing an attach or a restore, so how do you resolve this?


 EXEC sp_change_users_login 'REPORT'---find the orphan users

--First, make sure that this is the problem. This will lists the orphaned users:

EXEC sp_change_users_login 'Report'

--If you already have a login id and password for this user, fix it by doing:
--‘Auto_Fix’ attribute will create the user in SQL Server instance if it does not exist.

EXEC sp_change_users_login 'Auto_Fix', 'user'

--If you want to create a new login id and password for this user, fix it by doing:

EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'


Please see below post ::::
How To Avoid Orphaned Database Users with SQL Server Authentication
One common issue that database administrators often run into is the old, familiar “orphaned” user problem. This happens when you use SQL Server Authentication to create a SQL Server login on your database server. When you do this, SQL Server generates a unique SID for that SQL Server login. After you create the SQL Server login, you typically create a database user in a user database on that server instance, and associate the database user with that SQL Server login.
This works fine until you try to restore that user database to another SQL Server instance. If you previously created a SQL Server login with the same UserID on the new server, the SID for that SQL Server login will not match the database user in the user database that you have restored (from the other database instance). Hence the term “orphaned” user.  This is an especially big issue if you are using database mirroring, since your database users will be orphans when you failover from one instance to the other instance. It is also an issue with log shipping, and it often comes up when you migrate from an old database server to a new database server.
There are several ways to fix this, but the best thing (outside of just using Windows Authentication and avoiding the problem), is to create the new server login using the same SID as on the original server. Just like you see below:
-- Get Sids for all SQL Server logins on the old server instance
SELECT name, [sid] 
FROM sys.server_principals
WHERE [type] = 's'; 

-- Create new SQL Login on new server instance
IF  EXISTS (SELECT * FROM sys.server_principals WHERE name = N'SQLAppUser')
    DROP LOGIN SQLAppUser;
GO

-- Use the sid from the old server instance 
CREATE LOGIN SQLAppUser WITH PASSWORD = N'YourStrongPassword#', sid = 0x2F5B769F543973419BCEF78DE9FC1A64,
DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF;
GO

Performance Problem on Delete insert update : SSIS :solved

I had a SSIS package which runs multiple times


SSSI has :



Step 1:Execute SQL task:Delete from ABC table with some condition .
Step 2:Execute SQL task:Delete from XYZ table with some condition .

Then Step 3: Data flow task which has text file has Source and having various conditions and  inserting to ABC and XYZ tables

Then Step4:
Stored procedure which  Insert into another 10 tables  selecting data from ABC and XYZ based on conditions .


Here the stored procedure was taking 1 hr to complete , and some times it used to timeout calling from C# .....



So i looked at each individual Delete, Select, Inserts happening on SSIS ....
and i found there are few indexes on tables XYZ and ABC and there were lot of scans , user updates happening on indexes  and  these deletes , inserts happening longer time coz it has to delete/ insert/ update in data pages and index pages .
So
1.i dropped indexes before Delete , insert ( before step 1, 2,3 ) and
2. created the indexes, update statistics( which are not created by indexes)  before step 4 ...

This time SSIS package took 2 mins to run and i monitored for 1 week it is executing in 2mins  ...
Below Script helped me fining usage of indexes :
SELECT
    ObjectName      = object_schema_name(idx.object_id) + '.' + object_name(idx.object_id)
    ,IndexName      = idx.name
    ,IndexType      = CASE
                        WHEN is_unique = 1 THEN 'UNIQUE '
                        ELSE '' END + idx.type_desc
    ,User_Seeks     = us.user_seeks
    ,User_Scans     = us.user_scans
    ,User_Lookups   = us.user_lookups
    ,User_Updates   = us.user_updates
FROM sys.indexes idx
LEFT JOIN sys.dm_db_index_usage_stats us
    ON idx.object_id = us.object_id
    AND idx.index_id = us.index_id
    AND us.database_id = db_id()
WHERE object_schema_name(idx.object_id) != 'sys'
ORDER BY us.user_seeks + us.user_scans + us.user_lookups DESC



 Naresh ...11/26/13

Monday, August 19, 2013

Rename a Database

 Aug19th2013

 To Rename any user  Database you could follow the steps and to run the below querey you will require alter permissions on the database 


USE [master];
GO
ALTER DATABASE  OLDDATABASE  SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
EXEC sp_renamedb N'OLDDATABASE  ', N'NEWDATABASE ';
GO
ALTER DATABASE NEWDATABASE SET MULTI_USER


Back up the master database after you rename any database.

Tuesday, June 11, 2013

T-log backups taking too long to run during Normal hours

Hi,
I had a Application running for 2 hours which does run SSIS Packages , Inserts, Updates, Deletes on few databases and i have a Symantec log backup job which runs every 3 hours ...

We had huge performance problems Disk I/O , CPU , MEMORY everything was high , so 


I added few indexes, constantly monitored with Activity monitor , the last step of Application is to delete from history database tables and then insert in History database tables which  is taking long time to complete  also at the same time in parallel Symantec was doing a log  backing up history database log file(LDF) and doing a constancy check.
So I was positive that when backups are running mainly when Symantec starts backup of History database doing a consistency check and at the same time when the Application is trying to access History, Process database tables the process is taking longer than expected.

So after lot of research I  suggested to take  out Consistency check from backups  and then  log backups ran in 1 min and also the application ran good, with no huge DISK I/O and CPU hikes ..

Tip here is: 
do not run Constancy check during normal business hours .its high Disk I/O and CPU operation ,...


Thanks
Naresh
06/11/2013

Thursday, March 21, 2013

Maitanance Plan fails with error:Alter failed for Server 'servername'.




Hi , Today morning i saw my maintenance plan job to do differential backups got failed and i saw the error
Alter failed for Server 'servername'., oops i never saw this error , tried  goggling and found some help

so what happened was my Windows team  changed the CPU I/O Affinity settings and which made the changes to SQL Server

So to get your any maintenance plan running go ahead and run:
    sp_configure 'allow updates', 0

    reconfigure with override


and execute the Maintenance Job , it will run successfully  

Thanks
03/21/2013

Thursday, March 14, 2013

Differential Backup Job Fails

Hi,

I have 4 databases , all are in FULL recovery model :DB1,DB2,DB3,DB4....

I have taken full backups of DB1 , DB3, DB4 and i did not take DB2 full backup , now when i try take
differential backups of DB1,DB2,DB3,DB4 the job fails saying DB2 don't have a full backup,
what happens to DB1,DB3, DB4 database differential backups ?

The differential backups for DB1 , DB3 and  DB4 will be successful , SQL server job executes DB1 diff backups , then search for DB2 full backup, if not found it would go to DB3, then DB4 and do differential backups then throws the error saying DB2 don't have a Full backup ....


Thanks







Trigger : logs in table and email whenever a database is created or dropped and a object is created altered or dropped


the below script with steps included will create databses , tables and triggers under server and test databse
the AuditNewDatabaseCreation1 will emails and logs details in table whene ever a databse is created or dropped and Trigger:AuditObjects1 will be created in test database  and when ever a object is created , altered, dropped , it lohs information and emails


-----Step1: Create Database: AuditDatabase

-----Step2:Create table as below

USE [AuditDatabase]
 CREATE TABLE [dbo].[DatabaseCreateDropTracking](
    [TrackingId] [int] IDENTITY(1,1) NOT NULL,
    [TrackingDate] [datetime] NOT NULL,
    [DatabaseName] [varchar](100) NULL,
    [EventType] [varchar](100) NULL,
    [LoginName] [varchar](100) NULL,
    [InstanceName] [varchar](100) NULL,
    [SQLCommand] [nvarchar](max) NULL
) ON [PRIMARY]

ALTER TABLE [dbo].[DatabaseCreateDropTracking] ADD  CONSTRAINT [DF_DatabaseCreateDropTracking_TrackingDate]  DEFAULT (getdate()) FOR [TrackingDate]
GO

-----Step3:create table
USE [AuditDatabase]
--CREATE TABLE [dbo].[ObjectTracking](
    [TrackingId] [bigint] IDENTITY(1,1) NOT NULL,
    [TrackingDate] [datetime] NOT NULL,
    [DatabaseName] [varchar](500) NULL,
    [EventType] [varchar](500) NULL,
    [ObjectName] [varchar](500) NULL,
    [ObjectType] [varchar](500) NULL,
    [LoginName] [varchar](500) NULL,
    [HostName] [varchar](500) NULL,
    [SqlCommand] [nvarchar](max) NULL
) ON [PRIMARY]

ALTER TABLE [dbo].[ObjectTracking] ADD  DEFAULT (getdate()) FOR [TrackingDate]
GO

------Step4:THIS  below TRIGGERS EMAILS when a database is created or dropped  and keep track in tables in AuditDatabase   database

/****** Object:  DdlTrigger [AuditNewDatabaseCreation1]    Script Date: 03/14/2013 09:01:15 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE TRIGGER [AuditNewDatabaseCreation1]
ON ALL SERVER
FOR
-- DDL_DATABASE_LEVEL_EVENTS
-- Defining all the DDL database events on which we need track
CREATE_DATABASE, DROP_DATABASE
AS
BEGIN
--DECLARE @dbname varchar(500)
DECLARE @data XML
DECLARE @InstanceName varchar(100)
Declare @tsql varchar(max)
DECLARE @bd varchar(max)

--SET @dbname = DB_NAME()
SET @data = EVENTDATA()
SET @InstanceName = HOST_NAME()

INSERT INTO AuditDatabase.dbo.DatabaseCreateDropTracking(DatabaseName,EventType,LoginName,InstanceName,SqlCommand)
VALUES(
--@dbname,
@data.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'varchar(100)'),
@data.value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(100)'),
@data.value('(/EVENT_INSTANCE/LoginName)[1]', 'varchar(100)'),
@InstanceName,
@data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'varchar(max)')
)
 
Set @tsql = EVENTDATA().value
        ('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','varchar(max)')
SET @bd = 'UserName: ' + UPPER(SUSER_NAME()) + '

           ServerName: ' + @@SERVERNAME + '

           Time: '    + CONVERT(varchar(25),Getdate()) + '

           HostName: ' + HOST_NAME() + '

           Database: ' + db_name() + '

           T-SQL: ' +  @tsql
           
IF @bd LIKE '%drop%'
--;astratto@chesapeakebay.net

EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Database Mail ',
                             @recipients = 'xyz@abc.com',                      
                             @subject = 'A new database has been dropped ',
                             @body_format = 'HTML',
                             @importance = 'High',
                             @body = @bd
               

ELSE
--;astratto@chesapeakebay.net
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Database Mail',
                             @recipients = 'xyz@abc.com',                      
                             @subject = 'A new database has been created ',
                             @body_format = 'HTML',
                             @importance = 'High',
                             @body = @bd
               

END
GO

SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO

ENABLE TRIGGER [AuditNewDatabaseCreation1] ON ALL SERVER
GO

----STEP6:
CREATE DATABASE TEST
GO


USE [test]
GO

 CREATE  TRIGGER [AuditObjects1]
ON DATABASE
FOR
-- DDL_DATABASE_LEVEL_EVENTS
-- Defining all the DDL database events on which we need track
CREATE_PROCEDURE, ALTER_PROCEDURE, DROP_PROCEDURE,
CREATE_TABLE, ALTER_TABLE, DROP_TABLE,
CREATE_FUNCTION, ALTER_FUNCTION, DROP_FUNCTION,
CREATE_VIEW,ALTER_VIEW,DROP_VIEW,
CREATE_INDEX,ALTER_INDEX,DROP_INDEX
AS

BEGIN



DECLARE @data XML
DECLARE @HostName varchar(500)
SET @data = EVENTDATA()
SET @HostName = HOST_NAME()
Declare @tsql varchar(max)
DECLARE @bd varchar(max)



INSERT INTO AuditDatabase.dbo.ObjectTracking(DatabaseName,EventType,ObjectName,ObjectType,LoginName,HostName,SqlCommand)
VALUES(
@data.value('(/EVENT_INSTANCE/DatabaseName)[1]', 'varchar(500)'),
@data.value('(/EVENT_INSTANCE/EventType)[1]', 'varchar(500)'),
@data.value('(/EVENT_INSTANCE/ObjectName)[1]', 'varchar(500)'),
@data.value('(/EVENT_INSTANCE/ObjectType)[1]', 'varchar(500)'),
@data.value('(/EVENT_INSTANCE/LoginName)[1]', 'varchar(500)'),
@HostName,
@data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'varchar(max)')
)

Set @tsql = EVENTDATA().value
        ('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','varchar(max)')
       
SET @bd = 'UserName: ' + UPPER(SUSER_NAME()) + '

           ServerName: ' + @@SERVERNAME + '

           Time: '    + CONVERT(varchar(25),Getdate()) + '

           HostName: ' + HOST_NAME() + '

           Database: ' + db_name() + '

           T-SQL: ' +  @tsql
           

--PRINT 'Database has been created or dropped '
           
IF @bd LIKE '%CREATE%'
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'CBPO Database Mail Admins',
                             @recipients = 'xyz@abc.com',
                             @subject = 'An Object is created',
                             @body_format = 'HTML',
                             @importance = 'High',
                             @body = @bd
                           
   IF @bd LIKE '%ALTER%'
   EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Database Mail',
                             @recipients = 'xyz@abc.com',
                             @subject = 'An Object is altered  ',
                             @body_format = 'HTML',
                             @importance = 'High',
                             @body = @bd
                           
 
 
   IF @bd LIKE '%DROP%'    
      EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Database Mail',
                             @recipients = 'xyz@abc.com',
                             @subject = 'An Object is Dropped ',
                             @body_format = 'HTML',
                             @importance = 'High',
                             @body = @bd      
END


GO



ENABLE TRIGGER [AuditObjects1] ON DATABASE
GO


Friday, March 1, 2013

ADD identity to existing Table column


EX: I have a TABLE

CREATE TABLE tempdb
( recordid INT NOT NULL, NAME VARCHAR(10) NULL)
INSERT INTO tempdb VALUES ( 1, 'NICK')

Alter Table  dbo. tempdb
Add recordId  Int Identity(1, 1)
GO
----Column names in each table must be unique. Column name 'recordId' in table 'dbo.tempdb' is specified more than once.

 you cannot add the IDENTITY property to an existing column.

However, you can add a new IDENTITY column to the table:WITH similar NAME recordId1

Alter Table  dbo. tempdb
Add recordId1  Int Identity(1, 1)
GO
--THEN DROP  the old COLUMN recordId
ALTER TABLE tempdb
DROP COLUMN recordId


 rename the new COLUMN recordId1 TO recordId
sp_RENAME 'tempdb.recordid1', 'recordid' , 'COLUMN'
GO

refresh the table AND RIGHT click ON table  choose design change the physical location OF the COLUMN TO FIRST COLUMN

Thanks

Daily Checklist





I always keep this checklist with me 

 1. Check OS Event Logs and SQL Server Logs for all or specific events.
 2. Verify that all scheduled jobs have run successfully, if failed try to solve them depending on   the
        Type of job and priority.
 3. Check that backups have been made and successfully saved to a secure location.
 4. Monitor disk space to ensure your SQL Servers won’t run out of disk space. For best performance, all    disks should have 15% or more of free space. I keep a log of tempdb, and all user databases mdf and ldf in excel  
 5.  Regularly monitor and identify blocking issues. ( I do SP_WHO2) and
     SELECT * FROM sys.sysprocesses
 6. Create SQL Server alerts to notify you of potential problems like space alerts on all drives , and have them e-mailed to you.
 7. Regularly restore backups to a test server in order to verify that you can restore them. You don’t need to restore all backups every day, but do so often to ensure that you are confident you have good backups.
8.check and monitor index fragmentation %
  

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