Friday 24 January 2020

Get all non-clustered indexes

DECLARE cIX CURSOR FOR
    SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID
        FROM Sys.Indexes SI
            LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC ON SI.Name = TC.CONSTRAINT_NAME AND OBJECT_NAME(SI.Object_ID) = TC.TABLE_NAME
        WHERE TC.CONSTRAINT_NAME IS NULL
            AND OBJECTPROPERTY(SI.Object_ID, 'IsUserTable') = 1
        ORDER BY OBJECT_NAME(SI.Object_ID), SI.Index_ID

DECLARE @IxTable SYSNAME
DECLARE @IxTableID INT
DECLARE @IxName SYSNAME
DECLARE @IxID INT

-- Loop through all indexes
OPEN cIX
FETCH NEXT FROM cIX INTO @IxTable, @IxTableID, @IxName, @IxID
WHILE (@@FETCH_STATUS = 0)
BEGIN
    DECLARE @IXSQL NVARCHAR(4000) SET @IXSQL = ''
    SET @IXSQL = 'CREATE '

    -- Check if the index is unique
    IF (INDEXPROPERTY(@IxTableID, @IxName, 'IsUnique') = 1)
        SET @IXSQL = @IXSQL + 'UNIQUE '
    -- Check if the index is clustered
    IF (INDEXPROPERTY(@IxTableID, @IxName, 'IsClustered') = 1)
        SET @IXSQL = @IXSQL + 'CLUSTERED '

    SET @IXSQL = @IXSQL + 'INDEX ' + @IxName + ' ON ' + @IxTable + '('

    -- Get all columns of the index
    DECLARE cIxColumn CURSOR FOR
        SELECT SC.Name
        FROM Sys.Index_Columns IC
            JOIN Sys.Columns SC ON IC.Object_ID = SC.Object_ID AND IC.Column_ID = SC.Column_ID
        WHERE IC.Object_ID = @IxTableID AND Index_ID = @IxID
        ORDER BY IC.Index_Column_ID

    DECLARE @IxColumn SYSNAME
    DECLARE @IxFirstColumn BIT SET @IxFirstColumn = 1

    -- Loop throug all columns of the index and append them to the CREATE statement
    OPEN cIxColumn
    FETCH NEXT FROM cIxColumn INTO @IxColumn
    WHILE (@@FETCH_STATUS = 0)
    BEGIN
        IF (@IxFirstColumn = 1)
            SET @IxFirstColumn = 0
        ELSE
            SET @IXSQL = @IXSQL + ', '

        SET @IXSQL = @IXSQL + @IxColumn

        FETCH NEXT FROM cIxColumn INTO @IxColumn
    END
    CLOSE cIxColumn
    DEALLOCATE cIxColumn

    SET @IXSQL = @IXSQL + ')'
    -- Print out the CREATE statement for the index
    IF @IXSQL != '' BEGIN PRINT @IXSQL END

    FETCH NEXT FROM cIX INTO @IxTable, @IxTableID, @IxName, @IxID
END

CLOSE cIX
DEALLOCATE cIX

SQL SERVER – ReIndexing Database Tables

DECLARE @MyTable VARCHAR(255)
DECLARE myCursor
CURSOR FOR
SELECT '['+TABLE_SCHEMA+'].['+TABLE_NAME+']'
FROM information_schema.tables
WHERE table_type = 'base table'
OPEN myCursor
FETCH NEXT
FROM myCursor INTO @MyTable
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Reindexing Table:  ' + @MyTable
DBCC DBREINDEX(@MyTable, '', 80)
FETCH NEXT
FROM myCursor INTO @MyTable
END
CLOSE myCursor
DEALLOCATE myCursor
EXEC sp_updatestats

Monday 6 May 2019

Calculate number of months between two dates using javascript

var dtFrom= new Date('01/05/2019');
var dtTo= new Date('01/06/2021');

 var fromYear;
    var fromMonth = dtFrom.getMonth() + 1;
    var toYear;
    var toMonth = dtTo.getMonth() + 1;

    if ((fromYear = dtFrom.getFullYear()) < (toYear = dtTo.getFullYear())) {
        toMonth += (toYear - fromYear) * 12;
    }
    var diffMonths = toMonth - fromMonth;
    if (dtFrom.getDate() > dtTo.getDate()) diffMonths--;
   
-----------------------------------------------------------------------------
For get only the month diff

var dtFrom= new Date('01/05/2019');
var dtTo= new Date('01/06/2021');

 var monthCount = 0;
    while ((dtFrom.getMonth() + '' + dtFrom.getFullYear()) != (dtTo.getMonth() + '' + dtTo.getFullYear())) {
        monthCount++;
        dtFrom.setMonth(dtFrom.getMonth() + 1);
    }
    monthCount  = monthCount + 1;

Tuesday 23 April 2019

Remove special characters in a particular column

DECLARE @myString varchar(500), @validChars varchar(100)
SELECT @myString = 'sA123-\[]{}',@validChars = 'a-z0-9'

While @myString like '%[^' + @validChars + ']%'
Select @myString = replace(@myString,substring(@myString,patindex('%[^' + @validChars + ']%',@myString),1),'')

SELECT  @myString AS OutPutString

Tuesday 18 December 2018

How can I parse JSON with C#?


var jData = "{\"validationErrors\":[{\"description\":\"Employer Registration Number not found.\",\"code\":\"1003\",\"path\":\"employerRegistrationNumber\"}]}";

 var varData = JObject.Parse(jData);
            var varValidationErrorDetails = varData["validationErrors"];
            var varValidationErrorDescription = varValidationErrorDetails[0]["description"];
            string strValidationErrorDescription = Convert.ToString(varValidationErrorDescription).Replace("\r\n", "").Trim();

Tuesday 10 July 2018

Auto Query Generator In MSSQL Server

Before explaining the script, I want to share the reason to write this script and how it is helping my peers. We have code standard on the database side. Below points are standards.
  • Need to maintain a separate stored procedure to every table
  • Don’t use * in the query instead specify the column
  • Use the correct data type and size of a column
  • Every parameter should be nullable in a stored procedure.

CREATE PROC [dbo].[USP_QueryCreationSupport] (@table_Name varchar(100))
AS
BEGIN
    DECLARE @InserCols NVARCHAR(max)
    DECLARE @Inserparam NVARCHAR(max)
    DECLARE @Insertquery NVARCHAR(max)
    DECLARE @Selectquery NVARCHAR(max)
    DECLARE @Update NVARCHAR(max)
    DECLARE @DeleteQuery NVARCHAR(max)

    SELECT '@' + c.NAME + Space(1) + Case cast(t.Name as nvarchar(40))
                                         WHEN 'nvarchar' THEN
                                             t.NAME + '(' + cast(c.max_length as nvarchar(30)) + ')'
                                         WHEN 'varchar' THEN
                                             t.NAME + '(' + cast(c.max_length as nvarchar(30)) + ')'
                                         WHEN 'char' THEN
                                             t.NAME + '(' + cast(c.max_length as nvarchar(30)) + ')'
                                         WHEN 'decimal' THEN
                                             t.NAME + '(18,2)'
                                         ELSE
                                             t.name
                                     end + ' = null,' AS Params
FROM sys.columns c
        inner join sys.types t
            ON c.user_type_id = t.user_type_id
    WHERE c.object_id = object_id(@table_Name)

    SET @InserCols =
    (
        select distinct
            (
                select sc.NAME + ','
                FROM sys.tables st
                    inner join sys.columns sc
                        ON st.object_id = sc.object_id
                WHERE st.NAME = @table_Name
                for xml path(''), type
            ).value('.', 'NVARCHAR(MAX)')
    )
    SELECT @InserCols = LEFT(@InserCols, Len(@InserCols) - 1)

    SET @Inserparam =
    (
        select distinct
            (
                select '@' + sc.NAME + ','
                FROM sys.tables st
                    inner join sys.columns sc
                        ON st.object_id = sc.object_id
                WHERE st.NAME = @table_Name
                for xml path(''), type
            ).value('.', 'NVARCHAR(MAX)')
    )


    SELECT @Inserparam = LEFT(@Inserparam, Len(@Inserparam) - 1)

    SET @Insertquery = 'insert into ' + @table_Name + ' (' + @InserCols + ')' + ' values ' + ' (' + @Inserparam + ')'

    SELECT @Insertquery AS InsertQuery


    SET @Update =
    (
        select distinct
            (
                select sc.NAME + '= @' + sc.NAME + ','
                FROM sys.tables st
                    inner join sys.columns sc
                        ON st.object_id = sc.object_id
                WHERE st.NAME = @table_Name
                for xml path(''), type
            ).value('.', 'NVARCHAR(MAX)')
    )

    SELECT @Update = LEFT(@Update, Len(@Update) - 1)

    SET @Update = 'Update ' + @table_Name + ' set ' + @Update

    SELECT @Update AS UpdateQuery

    SET @Selectquery = 'select ' + @InserCols + ' from ' + @table_Name

    SELECT @Selectquery AS SelectQuery
END

--Execute the stored procedure and pass your table name as a parameter.
EXECUTE dbo.[USP_QueryCreationSupport] @table_Name = 'settings'

Sunday 8 July 2018

SQL SERVER – Custom TRIM Function

ALTER FUNCTION [dbo].[fn_Trim](@String NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
BEGIN
    RETURN LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@String,CHAR(10),'[]'),CHAR(13),'[]'),char(9),'[]'),CHAR(32),'[]'),'][',''),'[]',CHAR(32))));
END

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...