Thursday, December 22, 2022

Using Variables To Update and Increment the Value by 1

UPDATE accounts2 SET id = NULL GO DECLARE @id INT SET @id = 0 UPDATE accounts2 SET @id = id = @id + 10 GO SELECT * FROM accounts2 GO if you do not have any option to use Idenity column , the above will be helpful

Load Dim_date ( i have loaded 2023)

IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'DimDate')) BEGIN DROP TABLE DimDate END go GO CREATE TABLE [dbo].[DimDate] ( [DateKey] INT primary key, [Date] DATETIME, [FullDate] CHAR(10),-- Date in MM-dd-yyyy format [DayOfMonth] VARCHAR(2), -- Field will hold day number of Month [DayName] VARCHAR(9), -- Contains name of the day, Sunday, Monday [DayOfWeek] CHAR(1),-- First Day Sunday=1 and Saturday=7 [DayOfWeekInMonth] VARCHAR(2), --1st Monday or 2nd Monday in Month [DayOfWeekInYear] VARCHAR(2), [DayOfQuarter] VARCHAR(3), [DayOfYear] VARCHAR(3), [WeekOfMonth] VARCHAR(1),-- Week Number of Month [WeekOfQuarter] VARCHAR(2), --Week Number of the Quarter [WeekOfYear] VARCHAR(2),--Week Number of the Year [Month] VARCHAR(2), --Number of the Month 1 to 12 [MonthName] VARCHAR(9),--January, February etc [MonthOfQuarter] VARCHAR(2),-- Month Number belongs to Quarter [Quarter] CHAR(1), [QuarterName] VARCHAR(9),--First,Second.. [Year] CHAR(4),-- Year value of Date stored in Row [YearName] CHAR(7), --CY 2012,CY 2013 [MonthYear] CHAR(10), --Jan-2013,Feb-2013 [MMYYYY] CHAR(6), [FirstDayOfMonth] DATE, [LastDayOfMonth] DATE, [FirstDayOfQuarter] DATE, [LastDayOfQuarter] DATE, [FirstDayOfYear] DATE, [LastDayOfYear] DATE ) GO /********************************************************************************************/ --Specify Start Date and End date here --Value of Start Date Must be Less than Your End Date DECLARE @StartDate DATETIME = '01/01/2023' --Starting value of Date Range DECLARE @EndDate DATETIME = '12/31/2023' --End Value of Date Range --Temporary Variables To Hold the Values During Processing of Each Date of Year DECLARE @DayOfWeekInMonth INT, @DayOfWeekInYear INT, @DayOfQuarter INT, @WeekOfMonth INT, @CurrentYear INT, @CurrentMonth INT, @CurrentQuarter INT /*Table Data type to store the day of week count for the month and year*/ DECLARE @DayOfWeek TABLE (DOW INT, MonthCount INT, QuarterCount INT, YearCount INT) INSERT INTO @DayOfWeek VALUES (1, 0, 0, 0) INSERT INTO @DayOfWeek VALUES (2, 0, 0, 0) INSERT INTO @DayOfWeek VALUES (3, 0, 0, 0) INSERT INTO @DayOfWeek VALUES (4, 0, 0, 0) INSERT INTO @DayOfWeek VALUES (5, 0, 0, 0) INSERT INTO @DayOfWeek VALUES (6, 0, 0, 0) INSERT INTO @DayOfWeek VALUES (7, 0, 0, 0) --Extract and assign various parts of Values from Current Date to Variable DECLARE @CurrentDate AS DATETIME = @StartDate SET @CurrentMonth = DATEPART(MM, @CurrentDate) SET @CurrentYear = DATEPART(YY, @CurrentDate) SET @CurrentQuarter = DATEPART(QQ, @CurrentDate) /********************************************************************************************/ --Proceed only if Start Date(Current date ) is less than End date you specified above WHILE @CurrentDate < @EndDate BEGIN /*Begin day of week logic*/ /*Check for Change in Month of the Current date if Month changed then Change variable value*/ IF @CurrentMonth != DATEPART(MM, @CurrentDate) BEGIN UPDATE @DayOfWeek SET MonthCount = 0 SET @CurrentMonth = DATEPART(MM, @CurrentDate) END /* Check for Change in Quarter of the Current date if Quarter changed then change Variable value*/ IF @CurrentQuarter != DATEPART(QQ, @CurrentDate) BEGIN UPDATE @DayOfWeek SET QuarterCount = 0 SET @CurrentQuarter = DATEPART(QQ, @CurrentDate) END /* Check for Change in Year of the Current date if Year changed then change Variable value*/ IF @CurrentYear != DATEPART(YY, @CurrentDate) BEGIN UPDATE @DayOfWeek SET YearCount = 0 SET @CurrentYear = DATEPART(YY, @CurrentDate) END -- Set values in table data type created above from variables UPDATE @DayOfWeek SET MonthCount = MonthCount + 1, QuarterCount = QuarterCount + 1, YearCount = YearCount + 1 WHERE DOW = DATEPART(DW, @CurrentDate) SELECT @DayOfWeekInMonth = MonthCount, @DayOfQuarter = QuarterCount, @DayOfWeekInYear = YearCount FROM @DayOfWeek WHERE DOW = DATEPART(DW, @CurrentDate) /*End day of week logic*/ /* Populate Your Dimension Table with values*/ INSERT INTO [dbo].[DimDate] SELECT CONVERT (char(8),@CurrentDate,112) as DateKey, @CurrentDate AS Date, CONVERT (char(10),@CurrentDate,101) as FullDate, DATEPART(DD, @CurrentDate) AS DayOfMonth, DATENAME(DW, @CurrentDate) AS DayName, DATEPART(DW, @CurrentDate) AS DayOfWeek, @DayOfWeekInMonth AS DayOfWeekInMonth, @DayOfWeekInYear AS DayOfWeekInYear, @DayOfQuarter AS DayOfQuarter, DATEPART(DY, @CurrentDate) AS DayOfYear, DATEPART(WW, @CurrentDate) + 1 - DATEPART(WW, CONVERT(VARCHAR, DATEPART(MM, @CurrentDate)) + '/1/' + CONVERT(VARCHAR, DATEPART(YY, @CurrentDate))) AS WeekOfMonth, (DATEDIFF(DD, DATEADD(QQ, DATEDIFF(QQ, 0, @CurrentDate), 0), @CurrentDate) / 7) + 1 AS WeekOfQuarter, DATEPART(WW, @CurrentDate) AS WeekOfYear, DATEPART(MM, @CurrentDate) AS Month, DATENAME(MM, @CurrentDate) AS MonthName, CASE WHEN DATEPART(MM, @CurrentDate) IN (1, 4, 7, 10) THEN 1 WHEN DATEPART(MM, @CurrentDate) IN (2, 5, 8, 11) THEN 2 WHEN DATEPART(MM, @CurrentDate) IN (3, 6, 9, 12) THEN 3 END AS MonthOfQuarter, DATEPART(QQ, @CurrentDate) AS Quarter, CASE DATEPART(QQ, @CurrentDate) WHEN 1 THEN 'First' WHEN 2 THEN 'Second' WHEN 3 THEN 'Third' WHEN 4 THEN 'Fourth' END AS QuarterName, DATEPART(YEAR, @CurrentDate) AS Year, 'CY ' + CONVERT(VARCHAR, DATEPART(YEAR, @CurrentDate)) AS YearName, LEFT(DATENAME(MM, @CurrentDate), 3) + '-' + CONVERT(VARCHAR, DATEPART(YY, @CurrentDate)) AS MonthYear, RIGHT('0' + CONVERT(VARCHAR, DATEPART(MM, @CurrentDate)),2) + CONVERT(VARCHAR, DATEPART(YY, @CurrentDate)) AS MMYYYY, CONVERT(DATETIME, CONVERT(DATE, DATEADD(DD, - (DATEPART(DD, @CurrentDate) - 1), @CurrentDate))) AS FirstDayOfMonth, CONVERT(DATETIME, CONVERT(DATE, DATEADD(DD, - (DATEPART(DD, (DATEADD(MM, 1, @CurrentDate)))), DATEADD(MM, 1, @CurrentDate)))) AS LastDayOfMonth, DATEADD(QQ, DATEDIFF(QQ, 0, @CurrentDate), 0) AS FirstDayOfQuarter, DATEADD(QQ, DATEDIFF(QQ, -1, @CurrentDate), -1) AS LastDayOfQuarter, CONVERT(DATETIME, '01/01/' + CONVERT(VARCHAR, DATEPART(YY, @CurrentDate))) AS FirstDayOfYear, CONVERT(DATETIME, '12/31/' + CONVERT(VARCHAR, DATEPART(YY, @CurrentDate))) AS LastDayOfYear SET @CurrentDate = DATEADD(DD, 1, @CurrentDate) END /********************************************************************************************/ go SELECT * FROM [dbo].[DimDate] INSERT INTO dbo.DimDate ( DateKey, Date, FullDate, DayOfMonth, DayName, DayOfWeek, DayOfWeekInMonth, DayOfWeekInYear, DayOfQuarter, DayOfYear, WeekOfMonth, WeekOfQuarter, WeekOfYear, Month, MonthName, MonthOfQuarter, Quarter, QuarterName, Year, YearName, MonthYear, MMYYYY, FirstDayOfMonth, LastDayOfMonth, FirstDayOfQuarter, LastDayOfQuarter, FirstDayOfYear, LastDayOfYear ) VALUES ( 20231231, -- DateKey - int '2023-12-31 00:00:00.000', -- Date - datetime '12/31/2023', -- FullDate - char(10) '31', -- DayOfMonth - varchar(2) 'Sunday', -- DayName - varchar(9) '1', -- DayOfWeek - char(1) '6', -- DayOfWeekInMonth - varchar(2) '53', -- DayOfWeekInYear - varchar(2) '14', -- DayOfQuarter - varchar(3) '365', -- DayOfYear - varchar(3) '6', -- WeekOfMonth - varchar(1) '14', -- WeekOfQuarter - varchar(2) '53', -- WeekOfYear - varchar(2) '12', -- Month - varchar(2) 'December', -- MonthName - varchar(9) '3', -- MonthOfQuarter - varchar(2) '4', -- Quarter - char(1) 'Fourth', -- QuarterName - varchar(9) '2023', -- Year - char(4) 'CY 2023', -- YearName - char(7) 'Dec-2023 ', -- MonthYear - char(10) '122023', -- MMYYYY - char(6) '2023-12-01', -- FirstDayOfMonth - date '2023-12-31', -- LastDayOfMonth - date '2023-10-01', -- FirstDayOfQuarter - date '2023-12-31', -- LastDayOfQuarter - date '2023-01-01', -- FirstDayOfYear - date '2023-12-31' -- LastDayOfYear - date ) --another example --INSERT INTO [dbo].[Dim_Date] -- ([Date_Type] -- ,[Full_Date] -- ,[Full_Date_BI] -- ,[Year_Month_Number] -- ,[Year_Number] -- ,[Day_Of_Week_Number] -- ,[Day_Of_Month_Number] -- ,[Day_Of_Quarter_Number] -- ,[Day_Of_Year_Number] -- ,[Day_Name] -- ,[Week_Of_Month_Number] -- ,[Week_Of_Quarter_Number] -- ,[Week_Of_Year_Number] -- ,[Month_Of_Quarter_Number] -- ,[Month_Of_Year_Number] -- ,[Month_Name] -- ,[Abbr_Month_Name] -- ,[Quarter_Of_Year_Number] -- ,[Quarter_Name] -- ,[is_Today] -- ,[is_Current_Week] -- ,[is_Last_Week] -- ,[is_Current_Month] -- ,[is_Last_Month] -- ,[is_Last_Day_Of_Month] -- ,[is_Last_30_Days] -- ,[is_Last_28_Days] -- ,[is_Last_12_Weeks] -- ,[is_Last_12_Months] -- ,[is_Holiday] -- ,[Sales_Start_Time] -- ,[Sales_End_Time] -- ,[Support_Start_Time] -- ,[Support_End_Time] -- ,[Dialer_Start_Time] -- ,[Dialer_End_Time] -- ,[Lead_Business_Day] -- ,[Sale_Business_Day] -- ,[Shipping_Day_Num] -- ,[Insert_Audit_Key] -- ,[Update_Audit_Key]) SELECT 'Date' AS Date_type , [Date] AS FULL_date ,[Date] AS FULL_date_BI ,CASE WHEN [MonthName] = 'January' THEN '202301' WHEN [MonthName] = 'February' THEN '202302' WHEN [MonthName] = 'March' THEN '202303' WHEN [MonthName] = 'April' THEN '202304' WHEN [MonthName] = 'May' THEN '202305' WHEN [MonthName] = 'June' THEN '202306' WHEN [MonthName] = 'July' THEN '202307' WHEN [MonthName] = 'August' THEN '202308' WHEN [MonthName] = 'September' THEN '202309' WHEN [MonthName] = 'October' THEN '202310' WHEN [MonthName] = 'November' THEN '202311' WHEN [MonthName] = 'December' THEN '202312' ELSE NULL END AS Year_month_Number, [Year] AS Year_Number, [Dayofweek] AS Day_Of_Week_Number ,[dayofmonth] AS Day_of_Month_number ,dayofQuarter AS Day_of_Quarter_number---? Have to fix this ,[DayOFyear] AS day_of_year_number ,[dayname] AS Day_name ,[Weekofmonth] AS week_of_month_number ,[WeekofQuarter] AS week_of_Quarter_number ,WeekOfyear AS Week_of_year_number ,MonthofQuarter AS Month_Of_Quarter_number ,[Month] AS Month_of_year_number ,[MonthName] AS Month_name , CASE WHEN [MonthName] = 'January' THEN 'Jan' WHEN [MonthName] = 'February' THEN 'Feb' WHEN [MonthName] = 'March' THEN 'Mar' WHEN [MonthName] = 'April' THEN 'Apr' WHEN [MonthName] = 'May' THEN 'May' WHEN [MonthName] = 'June' THEN 'Jun' WHEN [MonthName] = 'July' THEN 'Jul' WHEN [MonthName] = 'August' THEN 'Aug' WHEN [MonthName] = 'September' THEN 'Sep' WHEN [MonthName] = 'October' THEN 'Oct' WHEN [MonthName] = 'November' THEN 'Nov' WHEN [MonthName] = 'December' THEN 'Dec' ELSE NULL END AS Abbr_month_name ,[Quarter] AS Quarter_of_Year_name ,Quartername AS Quarter_name ,0 AS is_today ,0 AS is_current_week ,0 AS is_last_week ,0 AS is_current_Month ,0 AS is_last_month ,0 AS is_last_day_of_month --case add here ---ned to fix case when month =02 and date 28 then 1 ---like that addd case ,0 AS is_last_30_Days ,0 AS is_last_28_days ,0 AS is_last_12_weeks ,0 AS is_last_12_months ,0 as is_holiday , CASE WHEN [DayName]= 'Sunday' THEN '10:00:00' WHEN [DayName]= 'Saturday' THEN '10:00:00' WHEN [DayName]= 'Friday' THEN '08:00:00' WHEN [DayName]= 'Thursday' THEN '08:00:00' WHEN [DayName]= 'Wednesday' THEN '08:00:00' WHEN [DayName]= 'Tuesday' THEN '08:00:00' WHEN [DayName]= 'Monday' THEN '08:00:00' ELSE NULL END AS sales_start_Time , CASE WHEN [DayName]='Sunday' THEN '19:00:00' WHEN [DayName]='Saturday' THEN '19:00:00' WHEN [DayName]='Friday' THEN '23:00:00' WHEN [DayName]='Thursday' THEN '23:00:00' WHEN [DayName]='Wednesday' THEN '23:00:00' WHEN [DayName]='Tuesday' THEN '23:00:00' WHEN [DayName]='Monday' THEN '23:00:00' ELSE NULL END AS sales_End_Time , CASE WHEN [DayName]='Sunday' THEN '19:00:00' WHEN [DayName]='Saturday' THEN '19:00:00' WHEN [DayName]='Friday' THEN '23:00:00' WHEN [DayName]='Thursday' THEN '23:00:00' WHEN [DayName]='Wednesday' THEN '23:00:00' WHEN [DayName]='Tuesday' THEN '23:00:00' WHEN [DayName]='Monday' THEN '23:00:00' ELSE NULL END AS Support_Start_Time , CASE WHEN [DayName]= 'Sunday' THEN '19:00:00' WHEN [DayName]= 'Saturday' THEN '19:00:00' WHEN [DayName]= 'Friday' THEN '23:00:00' WHEN [DayName]= 'Thursday' THEN '23:00:00' WHEN [DayName]= 'Wednesday' THEN '23:00:00' WHEN [DayName]= 'Tuesday' THEN '23:00:00' WHEN [DayName]= 'Monday' THEN '23:00:00' ELSE NULL END AS Support_End_Time , CASE WHEN [DayName]= 'Sunday' THEN '19:00:00' WHEN [DayName]= 'Saturday' THEN '19:00:00' WHEN [DayName]= 'Friday' THEN '23:00:00' WHEN [DayName]= 'Thursday' THEN '23:00:00' WHEN [DayName]= 'Wednesday' THEN '23:00:00' WHEN [DayName]= 'Tuesday' THEN '23:00:00' WHEN [DayName]= 'Monday' THEN '23:00:00' ELSE NULL END AS Dialer_Start_Time , CASE WHEN [DayName]= 'Sunday' THEN '19:00:00' WHEN [DayName]= 'Saturday' THEN '19:00:00' WHEN [DayName]= 'Friday' THEN '23:00:00' WHEN [DayName]= 'Thursday' THEN '23:00:00' WHEN [DayName]= 'Wednesday' THEN '23:00:00' WHEN [DayName]= 'Tuesday' THEN '23:00:00' WHEN [DayName]= 'Monday' THEN '23:00:00' ELSE NULL END AS Dialer_End_Time , CASE WHEN [DayName]= 'Sunday' THEN '0.39' WHEN [DayName]= 'Saturday' THEN '0.46' WHEN [DayName]= 'Friday' THEN '0.69' WHEN [DayName]= 'Thursday' THEN '0.75' WHEN [DayName]= 'Wednesday' THEN '0.83' WHEN [DayName]= 'Tuesday' THEN '0.84' WHEN [DayName]= 'Monday' THEN '1.00' ELSE NULL END AS Lead_Business_day , CASE WHEN [DayName]= 'Sunday' THEN '0.30' WHEN [DayName]= 'Saturday' THEN '0.70' WHEN [DayName]= 'Friday' THEN '0.71' WHEN [DayName]= 'Thursday' THEN '0.84' WHEN [DayName]= 'Wednesday' THEN '0.83' WHEN [DayName]= 'Tuesday' THEN '1,00' WHEN [DayName]= 'Monday' THEN '0.06' ELSE NULL END AS Lead_Business_day --,Shipping_day_num --have to fix this ---increment need to fix this , 681161 AS Insert_audit_key ,-1 AS Update_Audit_key FROM AuditDB.[dbo].[DimDate]

Wednesday, December 21, 2022

 USE [AuditDB]

GO


/****** Object:  Table [dbo].[NK_BlockingReport]    Script Date: 3/8/2022 12:41:56 PM ******/

SET ANSI_NULLS ON

GO


SET QUOTED_IDENTIFIER ON

GO


CREATE TABLE [dbo].[BlockingReport](

[ID] [INT] IDENTITY(1,1) NOT NULL,

[ObjectName] [sysname] NULL,

[BlockingObjectName] [sysname] NULL,

[StatementText] [VARCHAR](MAX) NULL,

[BlockingStatementText] [VARCHAR](MAX) NULL,

[SessionID] [INT] NULL,

[BlockingSessionID] [INT] NULL,

[Status] [VARCHAR](50) NULL,

[BlockingStatus] [VARCHAR](50) NULL,

[DateCreated] [DATETIME] NULL,

[DatabaseName] [VARCHAR](100) NULL,

[CPU] [BIGINT] NULL,

[RunningTime] [INT] NULL,

[RuuningFrom] [VARCHAR](800) NULL,

[RuuningBy] [VARCHAR](800) NULL,

[ProgramName] [VARCHAR](100) NULL,

[LoginName] [VARCHAR](100) NULL

) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO



USE [AuditDB]

GO


/****** Object:  Table [dbo].[Deadlock]    Script Date: 3/8/2022 12:42:43 PM ******/

SET ANSI_NULLS ON

GO


SET QUOTED_IDENTIFIER ON

GO


CREATE TABLE [dbo].[DeadlockReport](

[RecordId] [INT] IDENTITY(1,1) NOT NULL,

[AlertTime] [DATETIME] NOT NULL,

[DeadlockGraph] [XML] NULL,

[Notified] [INT] NOT NULL,

PRIMARY KEY CLUSTERED 

(

[RecordId] ASC

)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO


ALTER TABLE [dbo].[Deadlock] ADD  CONSTRAINT [DF_deadlock_flag]  DEFAULT ((0)) FOR [Notified]

GO



Alerts that should have in sql prod environments

Alert when long running qureies are found--every 2 hrs Alert Current SQL jobs are running -daily 8am SendJobFailureReport AlertSendIndexFragmentationdetails AvailabilityGroupsInfo Check Database Status Check For Missing Backups CheckAlwaysonSyncStatus-Every5minutes Collect_Database_Size_Info_Daily1am IndexFragmentationdetails-Shop-Every1Hour Notify when AG Replicas Disconnect SendSpaceAlert SQLRestart Notify TrackAvailabilityLatenc

Alert Index fragmentation report

DECLARE @Document NVARCHAR(MAX) , @DocumentHead NVARCHAR(MAX) , @DocumentTail NVARCHAR(MAX) , @TableHead NVARCHAR(MAX) , @TableBody NVARCHAR(MAX) , @TableTail NVARCHAR(MAX) , @page_count_minimum SMALLINT , @fragmentation_minimum INT; SET @page_count_minimum =1000; SET @fragmentation_minimum = 30; SET @DocumentHead = N'' + N'' + N'' + N'' + N'

' + N'Below are the Indexes in Workbench2Prod Database with Average Fragmentation above 30 Percent' + N'

'; SET @DocumentTail = ''; SET @TableHead = N'' + N'' + N' ' + N' ' + N' ' + N' ' + N''; SET @TableTail = '
TableNameIndexNameAverageFragmentationPercentPageCount
'; SELECT @TableBody = ( SELECT ROW_NUMBER() OVER ( ORDER BY avg_fragmentation_in_percent DESC ) % 2 AS [TRRow] , sys.objects.name AS [TD] , sys.indexes.name AS [TD] , CONVERT(VARCHAR(10), avg_fragmentation_in_percent, 121) AS [TD] , page_count AS [TD] FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'LIMITED') INNER JOIN sys.objects ON sys.objects.object_id = sys.dm_db_index_physical_stats.object_id INNER JOIN sys.indexes ON sys.indexes.index_id = sys.dm_db_index_physical_stats.index_id AND sys.indexes.object_id = sys.dm_db_index_physical_stats.object_id WHERE avg_fragmentation_in_percent > @fragmentation_minimum AND objects.is_ms_shipped = 0 AND sys.dm_db_index_physical_stats.index_id > 0 and sys.indexes.name<>'NIX_AccountTicketNote_AccountTicketID_TicketStateID'--Excluded This particular index Condition on may5th 2016 AND page_count > @page_count_minimum ORDER BY avg_fragmentation_in_percent DESC FOR XML RAW('tr') , ELEMENTS ); IF @TableBody IS NULL BEGIN RETURN; END; ELSE BEGIN SET @TableBody = REPLACE(@TableBody, '_x0020_', SPACE(1)); SET @TableBody = REPLACE(@TableBody, '_x003D_', '='); SET @TableBody = REPLACE(@TableBody, '1',''); SET @TableBody = REPLACE(@TableBody, '0', ''); SELECT @Document = @DocumentHead + @TableHead + @TableBody+ @TableTail + @DocumentTail; EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Default', @recipients ='abc@abc', @subject = 'Average Index Fragmentation with above 30 Percent', @body = @Document, @body_format = 'HTML'; END END

Capture blocking

--Table: /****** Object: Table [dbo].[NK_BlockingReport] Script Date: 12/21/2022 12:25:22 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[NK_BlockingReport]( [ID] [INT] IDENTITY(1,1) NOT NULL, [ObjectName] [sysname] NULL, [BlockingObjectName] [sysname] NULL, [StatementText] [VARCHAR](MAX) NULL, [BlockingStatementText] [VARCHAR](MAX) NULL, [SessionID] [INT] NULL, [BlockingSessionID] [INT] NULL, [Status] [VARCHAR](50) NULL, [BlockingStatus] [VARCHAR](50) NULL, [DateCreated] [DATETIME] NULL, [DatabaseName] [VARCHAR](100) NULL, [CPU] [BIGINT] NULL, [RunningTime] [INT] NULL, [RuuningFrom] [VARCHAR](800) NULL, [RuuningBy] [VARCHAR](800) NULL, [ProgramName] [VARCHAR](100) NULL, [LoginName] [VARCHAR](100) NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO --SP: /****** Object: StoredProcedure [dbo].[NK_SP_InsertBlockingRecords] Script Date: 12/21/2022 12:24:59 PM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO --Schedule Job to run sp and send email when alert happens ALTER PROC [dbo].[NK_SP_InsertBlockingRecords] AS INSERT INTO dbo.NK_BlockingReport (ObjectName,BlockingObjectName, StatementText,BlockingSessionID,BlockingStatementText, BlockingStatus,DateCreated,[Status],DatabaseName,CPU,RunningTime,RuuningFrom,RuuningBy,ProgramName,LoginName) SELECT W1.ObjectName AS ObjectName, W2.ObjectName AS BlockingObjectName, W1.Statement_Text AS BlockedStatementText, W2.sessionid AS BlockingSessionID, W2.Statement_Text AS BlockingStatementText, W2.status AS BlockingStatus, GETDATE() AS DateCreated, w1.[Status] AS CurrentStatus, w1.DatabaseName , w1.[CPU_time] , w2.[RunningMinutes] , w2.[RunningFrom] , w1.[RunningBy] , w1.[Program_Name] , w1.[Login_Name] FROM NK_SP_Active W1 INNER JOIN NK_SP_Active W2 ON W1.BlockingWith > 0 AND W1.BlockingWith = W2.sessionid; job: 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 EXEC NK_SP_InsertBlockingRecords END ELSE BEGIN RETURN END

SendJobFailureReport

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 DECLARE @Document NVARCHAR(MAX) , @DocumentHead NVARCHAR(MAX) , @DocumentTail NVARCHAR(MAX) , @TableHead NVARCHAR(MAX) , @TableBody NVARCHAR(MAX) , @TableTail NVARCHAR(MAX) , @Now DATETIME SET @DocumentHead = N'' + N'' + N'' + N'' + N'

' + N'The following Jobs failed in FPSQL1Listener SQL Server' + N'

'; SET @DocumentTail = ''; SET @TableHead = N'' + N'' + N' ' + N' ' + N' ' + N' ' + N' ' + N''; SET @TableTail = '
Server NameJob NameJob Failed DateTimeStatusError Message
'; SELECT @TableBody = (SELECT ROW_NUMBER() Over(Order By run_date) % 2 As [TRRow], T1.server AS [TD], SUBSTRING(T2.name,1,140) AS [TD], msdb.dbo.agent_datetime(run_date, run_time) as [TD], CASE T1.run_status WHEN 0 THEN 'Failed' WHEN 1 THEN 'Succeeded' WHEN 2 THEN 'Retry' WHEN 3 THEN 'Cancelled' WHEN 4 THEN 'In Progress' END AS [TD], T1.message AS [TD] FROM msdb..sysjobhistory T1 INNER JOIN msdb..sysjobs T2 ON T1.job_id = T2.job_id WHERE T1.run_status NOT IN (1, 4) AND T1.step_id != 0 AND run_date >= CONVERT(CHAR(8), (SELECT DATEADD (DAY,(-1), GETDATE())), 112) FOR XML RAW('tr'), ELEMENTS); --SELECT @TableBody IF @TableBody IS NULL BEGIN PRINT 'No Jobs failed'; RETURN; END ELSE BEGIN -- Replace the entity codes and row numbers SET @TableBody = Replace(@TableBody, '_x0020_', space(1)) SET @TableBody = Replace(@TableBody, '_x003D_', '=') SET @TableBody = Replace(@TableBody, '1', '') SET @TableBody = Replace(@TableBody, '0', ''); SELECT @Document = @DocumentHead + @TableHead + @TableBody + @TableTail + @DocumentTail EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Default' , @recipients= 'ABC@ABC.com' , @subject = 'Failed SQL Server Jobs on SQL' , @body = @Document , @body_format = 'HTML'; END END; ELSE BEGIN RETURN END

Alert when a login is created or dropped

ALTER TRIGGER LoginCreateDropTrigger ON ALL SERVER FOR CREATE_LOGIN, DROP_LOGIN AS BEGIN DECLARE @mailBody Nvarchar(MAX); DECLARE @data XML = EVENTDATA(); Declare @Mailsubject NVarchar(MAX) = 'Someone Created or Dropped a Login on SOX Server.As this is a SOX server, please create a ticket:' +@@SERVERNAME SET @mailBody = 'A new login was created on SQL Server: ' + @@SERVERNAME + ' ' + 'By user: ' + ISNULL(@data.value('(/EVENT_INSTANCE/LoginName)[1]', 'nvarchar(max)'), 'Null Login' ) + ' ' + + 'The TSql executed to do this was: ' + ISNULL(@data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(max)'), 'Null SQL ' )+ ' ' + 'At: ' + CONVERT(nvarchar, getdate(), 120) + ' ' + 'Please verify why this login was created and create a ticket if there is not' + ' ' ; Declare @bodyNew Nvarchar (Max) = Convert(Nvarchar(MAX),@data) Declare @SubjectNew Varchar(max)= 'As this is a SOX Server, Please create a Ticket'+CONVERT(VARCHAR(12),GETDATE(),107) EXECUTE MSDB.DBO.sp_send_dbmail @profile_name ='SQLMail' , @recipients = 'ABC @ABC.com', --this should be a distro @importance = 'High', @Subject=@Mailsubject, @body = @mailBody, @body_format = 'HTML' END ----DROP TRIGGER [LoginCreateDropTrigger] ON ALL SERVER go USE [master] CREATE LOGIN [TestNaresh] WITH PASSWORD=N'P@SSW)rd1@#$' MUST_CHANGE, DEFAULT_DATABASE=[master], CHECK_EXPIRATION=ON, CHECK_POLICY=ON GO DROP LOGIN [TestNaresh] go EXEC msdb.dbo.sysmail_start_sp; EXEC msdb.dbo.sysmail_help_status_sp;

Tuesday, December 20, 2022

How to stop and start DBmail

recently i was working on sending an email from the output of table and found below error: Msg 14641, Level 16, State 1, Procedure sp_send_dbmail, Line 81 Mail not queued. Database Mail is stopped. Use sysmail_start_sp to start Database Mail. and i was able to start db mail and send emal --START USE msdb GO EXEC dbo.sysmail_start_sp go --STOP USE msdb GO EXEC dbo.sysmail_stop_sp

Monday, December 19, 2022

Index rebuild online

  


DECLARE @page_count_minimum smallint     

DECLARE @fragmentation_minimum float

SET @page_count_minimum   =10

SET @fragmentation_minimum   = 10

SELECT

'ALTER INDEX ' + ' ['  +sys.indexes.name  + '] ' + 'On'+ ' ' + sys.objects.name + ' REBUILD  WITH (ONLINE = ON)'   as   b,sys.objects.name,

avg_fragmentation_in_percent AS frag,

page_count AS page_count,

sys.dm_db_index_physical_stats.object_id AS objectid, 

partition_number AS partitionnum

FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED')

inner join sys.objects 

on sys.objects.object_id = sys.dm_db_index_physical_stats.object_id

inner join sys.indexes 

on sys.indexes.index_id = sys.dm_db_index_physical_stats.index_id 

and sys.indexes.object_id = sys.dm_db_index_physical_stats.object_id

WHERE avg_fragmentation_in_percent > @fragmentation_minimum 

AND sys.dm_db_index_physical_stats.index_id > 0 

AND page_count > @page_count_minimum

ORDER BY  2  

go

 

-- can filter top 100 or select only table names by joining sysojbects and  can also get schema name by joining with schemas

 


select s.name as schema_name, s.schema_id, u.name as schema_owner from sys.schemas s inner join sys.sysusers u on u.uid = s.principal_id order by s.name


Rebuild index on very Large tables 1 TB table with 2K tables

Rebuild index on very Large tables 1 TB table with 2K tables


I had a situation where rebuilding the indexes ran for 1 day and filled the disk with 1.5TB.

and the log backups were taking ever and not truncating the log..what helped me to rebuild indexes and not to fill disk is below 



  • changed db to bulk recovery model from full
  • rebuild indexes 
  • changed db to FULL  recovery model  
also splitting tables of a very large db to do every nighht if we have a windows

UPDATE STATS WITH FULL SCAN is a must run when u migrate or upgrade SQL SERVER

We had some performance issues after migrating SQL Server from windows server 2012 to windows server 2019 and after analysis, I found that I should do

sp_msforeachtable 'UPDATE STATISTICS? WITH FULLSCAN'

or do individual tables 

This helped....



If you use FULLSCAN, it will read the entire table.

Question: When do you recommend using updated stats with FULLSCAN rather than default sampled?

Answer: When you know there is skew in the column.

Note: Skewed columns are columns in which the data is not evenly distributed among the rows.


Updating statistics ensures that queries compile with up-to-date statistics. Updating statistics via any process may cause query plans to recompile automatically.

Sunday, March 13, 2022

adding secondary file to an exiting database

 this is a online opertion and can be added in business hours 

say for example: 

disk E with MDF is almost full (only 10GB left), cannot shrink mdf and also disk cannot be extended , add a secondary files on F . this should help 

Tuesday, March 1, 2022

Backup report daily via sp and job everyday 9am

 EXEC..Backup_Report


@MailProfile = 'ABC' ,


@MailID = 'abc@abc.com',


@Server = 'ABC'



--keep sp and run job 9am everyday 


USE [master]

GO

/****** Object:  StoredProcedure [dbo].[Backup_Report]    Script Date: 3/1/2022 4:18:08 PM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO




ALTER PROCEDURE [dbo].[Backup_Report] (  

  @MailProfile NVARCHAR(200),   

  @MailID NVARCHAR(2000),  

  @Server VARCHAR(100) = NULL)  

AS  

BEGIN  

SET NOCOUNT ON;  

SET ARITHABORT ON;  

  

DECLARE @ServerName VARCHAR(100);  

SET @ServerName = ISNULL(@Server,@@SERVERNAME);  

  


  

CREATE TABLE #Backup_Report(  

ServerName VARCHAR(300),  

Database_name varchar(300),

BackupType varchar(50),

NotBackedUpSince varchar(100),

LastBackupDate VARCHAR(50),

Backuppath nvarchar(1000),

NotBackedUpSince_hours varchar(50));  

  

INSERT INTO #Backup_Report  


SELECT @@servername as ServerName,B.name as Database_Name ,  

case when A.type = 'D'  then 'Full'         

   when A.type = 'L' then 'Log'  

   When A.type ='I' then 'Diff' 

   

   end  as BackupType        ,     

   case                      

    when A.type = 'D'  then                                               

     ISNULL(STR(ABS(DATEDIFF(day, GetDate(),MAX(Backup_finish_date)))), 'NEVER')  + '-- Days'      

 

when A.type = 'I'  then                                               

     ISNULL(STR(ABS(DATEDIFF(day, GetDate(),MAX(Backup_finish_date)))), 'NEVER')  + '-- Days'     

              when A.type = 'L' then                                                             

                ISNULL(STR(ABS(DATEDIFF(minute, GetDate(),MAX(Backup_finish_date)))), 'NEVER')  + '-- Minutes'    

                           end        as NotBackedUpSince   

   ,              

                             ISNULL(Convert(char(20), MAX(backup_finish_date), 120), 'NEVER') as LastBackupDate   

                                          ,             

              max(convert(char(100),physical_device_name)) as BackupPath  ,

--  case when A.type = 'D'  then 'Full'         

   --when A.type = 'L' then 'Log'  

   --When A.type ='I' then 'Diff' 

   

   --end  as BackupType        ,     

   case                      

    when A.type = 'D'  then                                               

     ISNULL(STR(ABS(DATEDIFF(hour, GetDate(),MAX(Backup_finish_date)))), 'NEVER')        

 

when A.type = 'I'  then                                               

     ISNULL(STR(ABS(DATEDIFF(Hour, GetDate(),MAX(Backup_finish_date)))), 'NEVER')       

              when A.type = 'L' then                                                             

                ISNULL(STR(ABS(DATEDIFF(minute, GetDate(),MAX(Backup_finish_date)))), 'NEVER')     

                           end        as NotBackedUpSince_hours   

       FROM master.dbo.sysdatabases B LEFT OUTER JOIN msdb.dbo.backupset A   

       ON A.database_name = B.name 

                     left outer join msdb..backupmediafamily C       

                          on C.media_set_id = A.media_set_id 

                           where B.name not in ('tempdb') 

   --and A.type ='D'

   GROUP BY B.Name,A.type order by 1

  

  


  

/*************************************************************/  

/****************** HTML Preparation *************************/  

/*************************************************************/  

  

DECLARE @TableHTML  VARCHAR(MAX),                                    

  @StrSubject VARCHAR(100),                                    

  @Oriserver VARCHAR(100),                                

  @Version VARCHAR(250),                                

  @Edition VARCHAR(100),                                

  @ISClustered VARCHAR(100),                                

  @SP VARCHAR(100),                                

  @ServerCollation VARCHAR(100),                                

  @SingleUser VARCHAR(5),                                

  @LicenseType VARCHAR(100),                                

  @Cnt int,           

  @URL varchar(1000),                                

  @Str varchar(1000),                                

  @NoofCriErrors varchar(3)       

  

-- Variable Assignment              

  

SELECT @Version = @@version                                

SELECT @Edition = CONVERT(VARCHAR(100), serverproperty('Edition'))                                

SET @Cnt = 0                                

IF serverproperty('IsClustered') = 0                                 

BEGIN                                

 SELECT @ISClustered = 'No'                                

END                                

ELSE        

BEGIN                                

 SELECT @ISClustered = 'YES'                                

END                                

              

SELECT @OriServer = CONVERT(VARCHAR(50), SERVERPROPERTY('servername'))                                  

SELECT @strSubject = 'Backup Report ('+ CONVERT(VARCHAR(100), @SERVERNAME) + ')'                                    

   

  

  

    SET @TableHTML =                                    

 '<font face="Verdana" size="4">Backup Report</font>                                  

 <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="47%" id="AutoNumber1" height="50">                                  

 <tr>                                  

 <td width="39%" height="22" bgcolor="#000080"><b>                           

 <font face="Verdana" size="2" color="#FFFFFF">Server Name</font></b></td>                                  

 </tr>                                  

 <tr>                                  

 <td width="39%" height="27"><font face="Verdana" size="2">' + @ServerName +'</font></td>                                  

 </tr>                                  

 </table>     

 

 <table id="AutoNumber1" style="BORDER-COLLAPSE: collapse" borderColor="#111111" height="40" cellSpacing="0" cellPadding="0" width="933" border="1">                                

 <tr>                                

                             

                

     

                            

                              

 </table>                                

     <table style="BORDER-COLLAPSE: collapse" borderColor="#111111" cellPadding="0" width="933" bgColor="#ffffff" borderColorLight="#000000" border="1">                                  

 <tr>                                

                          

 </tr>'                            

          

        

   SELECT                                   

 @TableHTML =  @TableHTML +                              

 '</table>                                  

 <p style="margin-top: 1; margin-bottom: 0">&nbsp;</p>                                  

 <font face="Verdana" size="4">Backup Report</font>                                  

 <table id="AutoNumber1" style="BORDER-COLLAPSE: collapse" borderColor="#111111" height="40" cellSpacing="0" cellPadding="0" width="933" border="1">                                  

   <tr>                

 <th align="left" width="300" bgColor="#000080">                                    

 <font face="Verdana" size="1" color="#FFFFFF">ServerName</font></th>                              

  <th align="left" width="200" bgColor="#000080">               

 <font face="Verdana" size="1" color="#FFFFFF">Database_Name</font></th>  

 <th align="left" width="136" bgColor="#000080">                                    

 <font face="Verdana" size="1" color="#FFFFFF">BackupType</font></th>  

 <th align="left" width="136" bgColor="#000080">                                    

 <font face="Verdana" size="1" color="#FFFFFF">NotBackedupsince</font></th>  

 <th align="left" width="136" bgColor="#000080">                                    

 <font face="Verdana" size="1" color="#FFFFFF">lastBackupDate</font></th>  

 <th align="left" width="136" bgColor="#000080">                                    

 <font face="Verdana" size="1" color="#FFFFFF">backuppath</font></th>  


   </tr>'                                  

SELECT      

 @TableHTML =  @TableHTML +                                       

 '<tr>                                    

 <td><font face="Verdana" size="1">' + ISNULL(CONVERT(VARCHAR(100),  ServerName), '')  +'</font></td>' +                                        

 '<td><font face="Verdana" size="1">' + ISNULL(CONVERT(VARCHAR(100),  Database_Name), '')  +'</font></td>' +   

  '<td><font face="Verdana" size="1">' + ISNULL(CONVERT(VARCHAR(100),  BackupType), '')  +'</font></td>' + 


  CASE WHEN NotBackedUpSince_hours > 170 and backuptype = 'Full' THEN 

  '<td><font face="Verdana" size="1" color="#FF0000"><b>' + ISNULL(CONVERT(VARCHAR(100),  NotBackedupsince), '')  +'</font></td>'  

   WHEN NotBackedUpSince_hours >30 and BackupType  = 'Diff' THEN 

   '<td><font face="Verdana" size="1" color="#FF0000"><b>' + ISNULL(CONVERT(VARCHAR(100),  NotBackedupsince), '')  +'</font></td>'  

     WHEN NotBackedUpSince_hours >30 and BackupType  = 'Log' THEN 

   '<td><font face="Verdana" size="1" color="#FF0000"><b>' + ISNULL(CONVERT(VARCHAR(100),  NotBackedupsince), '')  +'</font></td>'

  ELSE 


   

  


    '<td><font face="Verdana" size="1">' + ISNULL(CONVERT(VARCHAR(100),  NotBackedupsince), '')  +'</font></td>' 

   END +

    '<td><font face="Verdana" size="1">' + ISNULL(CONVERT(VARCHAR(1000),  lastBackupDate), '')  +'</font></td>' + 

'<td><font face="Verdana" size="1">' + ISNULL(CONVERT(VARCHAR(1000),  backuppath), '')  +'</font></td>' + 

  '</tr>'                                  

FROM             

 #Backup_Report  

   

  

        

    

EXEC msdb.dbo.sp_send_dbmail                                    

 @profile_name = @MailProfile,--'MMStuckup',                             

 @recipients=@MailID,  --'uday.arumilli@ge.com',                                  

 @subject = @strSubject,                                   

 @body = @TableHTML,                                      

 @body_format = 'HTML' ;                             

  

  DROP TABLE   #Backup_Report; 

SET NOCOUNT OFF;  

SET ARITHABORT OFF;  

END  

  

  

  



send job failure report

 


 

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


DECLARE @Document NVARCHAR(MAX)

      , @DocumentHead NVARCHAR(MAX)

      , @DocumentTail NVARCHAR(MAX)

      , @TableHead NVARCHAR(MAX)

      , @TableBody NVARCHAR(MAX)

      , @TableTail NVARCHAR(MAX)

      , @Now DATETIME 

  


SET @DocumentHead = N'<html><head>'

                  + N'<style>'

                  + N'th, td'

                  + N'{ '

                  + N'  border: solid black 1px;'

                  + N'  padding: 1px 5px 1px 5px;'

                  + N'  font-size: 11pt;'

                  + N'}'

                  + N'</style>'

                  + N'</head>'

                  + N'<body>'

                  + N'<h3>'

                  + N'The following Jobs failed in FPSQL1Listener SQL Server'

                  + N'</h3>';


SET @DocumentTail = '</body></html>';


SET @TableHead = N'<table cellpadding=0 cellspacing=0 border=0>'

   + N'<tr bgcolor=#C0C0C0>'

   + N'  <th>Server Name</th>'

   + N'  <th>Job Name</th>'

   + N'  <th>Job Failed DateTime</th>'

+ N'  <th>Status</th>'

   + N'  <th>Error Message</th>'

   + N'</tr>';


SET @TableTail = '</table>';


SELECT @TableBody = (SELECT ROW_NUMBER() Over(Order By run_date) % 2 As [TRRow],

T1.server AS [TD],

SUBSTRING(T2.name,1,140) AS [TD],

msdb.dbo.agent_datetime(run_date, run_time) as [TD],

CASE T1.run_status

WHEN 0 THEN 'Failed'

WHEN 1 THEN 'Succeeded'

WHEN 2 THEN 'Retry'

WHEN 3 THEN 'Cancelled'

WHEN 4 THEN 'In Progress'

END AS [TD],

T1.message AS [TD] 

FROM msdb..sysjobhistory T1 INNER JOIN msdb..sysjobs T2 ON T1.job_id = T2.job_id

WHERE T1.run_status NOT IN (1, 4) AND T1.step_id != 0 AND run_date >= CONVERT(CHAR(8), (SELECT DATEADD (DAY,(-1), GETDATE())), 112)

FOR XML RAW('tr'), ELEMENTS);   


--SELECT @TableBody


IF @TableBody IS NULL 

BEGIN 

PRINT 'No Jobs failed';

RETURN; 

END

ELSE 

BEGIN

-- Replace the entity codes and row numbers

SET @TableBody = Replace(@TableBody, '_x0020_', space(1))

SET @TableBody = Replace(@TableBody, '_x003D_', '=')

SET @TableBody = Replace(@TableBody, '<tr><TRRow>1</TRRow>', '<tr bgcolor=#C6CFFF>')

SET @TableBody = Replace(@TableBody, '<TRRow>0</TRRow>', '');


SELECT @Document = @DocumentHead + @TableHead + @TableBody + @TableTail + @DocumentTail


EXEC msdb.dbo.sp_send_dbmail

@profile_name =  'Default'

, @recipients= 'SQL1Operator@frontpointsecurity.com'

, @subject = 'Failed SQL Server Jobs on SQL1'

, @body = @Document

, @body_format = 'HTML';

 


END

END;


ELSE 

BEGIN 

RETURN

END


Alert index fragmentatondetails

 USE [WorkBench2Prod]

GO

/****** Object:  StoredProcedure [dbo].[AlertSendIndexFragmentationdetails_Job_Step1]    Script Date: 3/1/2022 4:13:33 PM ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO


 ALTER Proc [dbo].[AlertSendIndexFragmentationdetails_Job_Step1]

 AS

 BEGIN 

  


/*

Author:Naresh DBA

Date: 04/01/2016

Purpose:Send Index fragmentation details every 1 hour

Paremeters: page_count_minimum = 1000 and fragmentation_minimum = 30

  

*/


DECLARE 

@Document NVARCHAR(MAX) ,

@DocumentHead NVARCHAR(MAX) ,

@DocumentTail NVARCHAR(MAX) ,

@TableHead NVARCHAR(MAX) ,

@TableBody NVARCHAR(MAX) ,

@TableTail NVARCHAR(MAX) ,

@page_count_minimum SMALLINT ,

@fragmentation_minimum INT;

  

SET @page_count_minimum =1000;

SET @fragmentation_minimum = 30;


SET @DocumentHead = N'<html><head>' + N'<style>' + N'th, td' + N'{ '

    + N'  border: solid black 1px;' + N'  padding: 1px 5px 1px 5px;'

    + N'  font-size: 11pt;' + N'}' + N'</style>' + N'</head>' + N'<body>'

    + N'<h3>'

    + N'Below are the Indexes in Workbench2Prod Database with Average Fragmentation above 30 Percent'

    + N'</h3>';


SET @DocumentTail = '</body></html>';


SET @TableHead = N'<table cellpadding=0 cellspacing=0 border=0>'

    + N'<tr bgcolor=#C0C0C0>' + N'  <th>TableName</th>'

    + N'  <th>IndexName</th>' + N'  <th>AverageFragmentationPercent</th>'

    + N'  <th>PageCount</th>' + N'</tr>';


SET @TableTail = '</table>';


SELECT  @TableBody = ( SELECT   ROW_NUMBER() OVER ( ORDER BY avg_fragmentation_in_percent DESC )

                                % 2 AS [TRRow] ,

                                sys.objects.name AS [TD] ,

                                sys.indexes.name AS [TD] ,

                                CONVERT(VARCHAR(10), avg_fragmentation_in_percent, 121) AS [TD] ,

                                page_count AS [TD]

                       FROM     sys.dm_db_index_physical_stats(DB_ID(), NULL,

                                                              NULL, NULL,

                                                              'LIMITED')

                                INNER JOIN sys.objects ON sys.objects.object_id = sys.dm_db_index_physical_stats.object_id

                                INNER JOIN sys.indexes ON sys.indexes.index_id = sys.dm_db_index_physical_stats.index_id

                                                          AND sys.indexes.object_id = sys.dm_db_index_physical_stats.object_id

                       WHERE    avg_fragmentation_in_percent > @fragmentation_minimum

                                AND objects.is_ms_shipped = 0

                                AND sys.dm_db_index_physical_stats.index_id > 0 and sys.indexes.name<>'NIX_AccountTicketNote_AccountTicketID_TicketStateID'--Excluded This particular index  Condition on may5th 2016

                                AND page_count > @page_count_minimum

                       ORDER BY avg_fragmentation_in_percent DESC

                     FOR

                       XML RAW('tr') ,

                           ELEMENTS

                     );

 


IF @TableBody IS NULL

    BEGIN 

        RETURN; 

    END;


ELSE

    BEGIN

 

        SET @TableBody = REPLACE(@TableBody, '_x0020_', SPACE(1));

        SET @TableBody = REPLACE(@TableBody, '_x003D_', '=');

        SET @TableBody = REPLACE(@TableBody, '<tr><TRRow>1</TRRow>','<tr bgcolor=#C6CFFF>');

        SET @TableBody = REPLACE(@TableBody, '<TRRow>0</TRRow>', '');

        SELECT  @Document = @DocumentHead + @TableHead + @TableBody+ @TableTail + @DocumentTail;


EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Default',

            @recipients ='AlertIndexFragmentationDetails@frontpoint.com',

-- 'naresh.koudagani@frontpointsecurity.com;mark.hildreth@frontpointsecurity.com',

            @subject = 'Average Index Fragmentation with above 30 Percent',

            @body = @Document, 

@body_format = 'HTML';

    END

END 

Wednesday, January 19, 2022

The connection type "AzureStorage" specified for connection manager "SSIS Connection Manager for Azure Storage" is not recognized as a valid connection manager type

 I was trying to upload CSV files to Azure using SSIS blob upload task 

received many errors


1. The connection type "AzureStorage" specified for connection manager "SSIS Connection Manager for Azure Storage" is not recognized as a valid connection manager type


2.Executed as user: FPSSI\sa_SQLSvcAdmin. Microsoft (R) SQL Server Execute Package Utility  Version 13.0.5026.0 for 64-bit  Copyright (C) 2016 Microsoft. All rights reserved.    Started:  1:34:04 PM  Error: 2022-01-19 13:34:05.29     Code: 0xC0016016     Source: Copy2Azure      Description: Failed to decrypt protected XML node "AccountKey" with error 0x8009000B "Key not valid for use in specified state.". You may not be authorized to access this information. This error occurs when there is a cryptographic error. Verify that the correct key is available.  End Error  Error: 2022-01-19 13:34:05.37     Code: 0x00000000     Source: Copy2Azure Connection manager "SSIS Connection Manager for Azure Storage" (SSIS Connection Manager for Azure Storage)     Description: Property "AccountKey" is not specified.  End Error  Error: 2022-01-19 13:34:05.37     Code: 0xC001401D     Source: Copy2Azure      Description: Connection "SSIS Connection Manager for Azure Storage" failed validation.  End Error  Error: 2022-01-19 13:34:05.39     Code: 0x00000000     Source: Copy2Azure Connection manager "SSIS Connection Manager for Azure Storage" (SSIS Connection Manager for Azure Storage)     Description: Property "AccountKey" is not specified.  End Error  Error: 2022-01-19 13:34:05.39     Code: 0x00000000     Source: Copy2Azure Connection manager "SSIS Connection Manager for Azure Storage" (SSIS Connection Manager for Azure Storage)     Description: Property "AccountKey" is not specified.  End Error  DTExec: The package execution returned DTSER_FAILURE (1).  Started:  1:34:04 PM  Finished: 1:34:05 PM  Elapsed:  0.5 seconds.  The package execution failed.  The step failed.

issue was:

  • SQL SERVER 2016
  • VS is 2017  
  • Installed Azure SSIS Feature pack 2017 

solution was:

  • SQL SERVER 2016
  • VS is 2017 but saved package as SSDT 2016 and modified the package with password
  • Azure SSIS Feature pack 2016 we have both 64 and 32 bit on dev server (uninstall 2017)


put password in command line
script out and see if its there or not, GUI not visible 

Option "OFF" is not valid. The command line parameters are invalid.The step failed SQL Agent job error while running package with password

 Option "Off" is not valid. The command-line parameters are invalid.The step failed

SQL Agent job error while running package with password 


make sure you did not remove any space while adding /DECRYPT Password

at edit command line manually.


I removed some space and got the error, but got fixed after re doing it with out any space 

Monday, January 3, 2022

failed to start project exception deserializing the package "The process cannot access the file because it is being used by another process."

Exception deserializing the package 

 "The process cannot access the file because it is being used by another process."

 

TITLE: Microsoft Visual Studio

------------------------------

Failed to start project

------------------------------

 

While running SSIS package i got the error “The process cannot access the file ‘*.ispac’ because it is being used by another process”.

 

The solution?/Fix:

1. Go to Task Manager

2. Details Tab.

3. Locate the process “DtsDebugHost.exe“.

4. Kill this process. There might be multiple instances of this process. Kill all of them.

5. Reexecute SSIS package

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