Saturday, 12 November 2016

Fastest way to find row count of all tables in SQL

SELECT T.name AS [TABLE NAME],
       I.rows AS [ROWCOUNT]
FROM   sys.tables AS T
       INNER JOIN sys.sysindexes AS I
               ON T.object_id = I.id
                  AND I.indid < 2
ORDER  BY I.rows DESC

Saturday, 8 October 2016

How to kill/Terminate all running process on Sql Server

alter database current set single_user with rollback immediate;
go
alter database current set multi_user;
go

Saturday, 11 June 2016

Check Database FIle Property

To check the database file property in sql server -


SELECT
    [TYPE] = A.TYPE_DESC
    ,[FILE_Name] = A.name
    ,[FILEGROUP_NAME] = fg.name
    ,[File_Location] = A.PHYSICAL_NAME
    ,[FILESIZE_MB] = CONVERT(DECIMAL(10,2),A.SIZE/128.0)
    ,[USEDSPACE_MB] = CONVERT(DECIMAL(10,2),A.SIZE/128.0 - ((SIZE/128.0) - CAST(FILEPROPERTY(A.NAME, 'SPACEUSED') AS INT)/128.0))
    ,[FREESPACE_MB] = CONVERT(DECIMAL(10,2),A.SIZE/128.0 - CAST(FILEPROPERTY(A.NAME, 'SPACEUSED') AS INT)/128.0)
    ,[FREESPACE_%] = CONVERT(DECIMAL(10,2),((A.SIZE/128.0 - CAST(FILEPROPERTY(A.NAME, 'SPACEUSED') AS INT)/128.0)/(A.SIZE/128.0))*100)
    ,[AutoGrow] = 'By ' + CASE is_percent_growth WHEN 0 THEN CAST(growth/128 AS VARCHAR(10)) + ' MB -'
        WHEN 1 THEN CAST(growth AS VARCHAR(10)) + '% -' ELSE '' END
        + CASE max_size WHEN 0 THEN 'DISABLED' WHEN -1 THEN ' Unrestricted'
            ELSE ' Restricted to ' + CAST(max_size/(128*1024) AS VARCHAR(10)) + ' GB' END
        + CASE is_percent_growth WHEN 1 THEN ' [autogrowth by percent, BAD setting!]' ELSE '' END
FROM sys.database_files A LEFT JOIN sys.filegroups fg ON A.data_space_id = fg.data_space_id
order by A.TYPE desc, A.NAME;


Monday, 30 May 2016

asmx return json example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web.Script.Serialization;  

namespace MYTEST
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    [ScriptService]
    public class MYTESTDATA : System.Web.Services.WebService
    {

        SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
        SqlCommand cmd;    
        SqlDataAdapter adp;
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void GetLevel()
        {
            DataTable ds = new DataTable("Kamal");
            con.Open();
            cmd = new SqlCommand("Proc_APP_GETLEVEL", con);
            cmd.CommandType = CommandType.StoredProcedure;
            adp = new SqlDataAdapter(cmd);
            adp.Fill(ds);    
            this.Context.Response.ContentType = "application/json; charset=utf-8";
            this.Context.Response.Write(CreateJsonParameters(ds));
        }
        [WebMethod]
      [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public void GetLevelWiseData(int LevelId)
        {
            DataTable ds = new DataTable("Kamal");
            con.Open();
            cmd = new SqlCommand("Proc_APP_GETLEVELWISEDATA", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@LevelId", SqlDbType.DateTime).Value = LevelId;//State-code
            adp = new SqlDataAdapter(cmd);
            adp.Fill(ds);
            this.Context.Response.ContentType = "application/json; charset=utf-8";
            this.Context.Response.Write(CreateJsonParameters(ds));


        }
        private string CreateJsonParameters(DataTable dt)
        {
     
            StringBuilder JsonString = new StringBuilder();
            //Exception Handling
            if (dt != null)//&& dt.Rows.Count > 0
            {
                JsonString.Append("{ ");
                JsonString.Append("\"Result\":[ ");

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    JsonString.Append("{ ");
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        if (j < dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() +
                                  "\":" + "\"" +
                                  dt.Rows[i][j].ToString() + "\",");
                        }
                        else if (j == dt.Columns.Count - 1)
                        {
                            JsonString.Append("\"" +
                               dt.Columns[j].ColumnName.ToString() + "\":" +
                               "\"" + dt.Rows[i][j].ToString() + "\"");
                        }
                    }
                                    
                    if (i == dt.Rows.Count - 1)
                    {
                        JsonString.Append("} ");
                    }
                    else
                    {
                        JsonString.Append("}, ");
                    }
                }

                JsonString.Append("]}");
                return JsonString.ToString();
            }
            else
            {
                return null;
            }
        }
    
  
      
    }
}

Saturday, 28 May 2016

Find duplicate row in excel

Format >> Conditional formatting


Formula -  =COUNTIF($A$1:$A$11,$A1)>1

Filtered records as below -



Friday, 27 May 2016

Refresh Page Issue in ASP.Net

Introduction

In Web Programming, the refresh click or postback is the big problem which generally developers face. So in order to avoid the refresh page issues like, if user refreshes the page after executing any button click event/method, the same method gets executed again on refresh. But this should not happen, so here is the code to avoid such issues.

Using the Code

Here the page's PreRender event and ViewState variable helps to differentate between the Button click event call or the Refresh page event call. For example, We have a web page having button to display text entered in text box to the Label.
So when page is first time loaded, then a session["update"] object is assigned by some unique value, and then the PreRender event is being called, where that session is assigned to the viewstate variable.
And on button click event, the session assigning code from page load will never called, as it is postback, so it directly calls the button click event where there is check whether the session and viewstate variables have same value. Here both values will be same. At the end of the click event method, the session variable is assigned with new unique value. Then always after click event, the PreRender event gets called where that newly assigned session value is assigned to viewstate variable.
So whenever the page is being refreshed, viewstate value will become previous value (previous value is taken from viewstate hidden control) which will never match with current session value. So whenever the control goes in button click event, the match condition never gets satisfied hence code related to button click never gets executed.

Points of Interest

Here we can understand the page events flow as well as Viewstate variable's workflow easily.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack) // If page loads for first time
    {
        // Assign the Session["update"] with unique value
        Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); 
        //=============== Page load code =========================




        //============== End of Page load code ===================
    }
}

protected void btnDisplay_Click(object sender, EventArgs e)
{ 
    // If page not Refreshed
    if (Session["update"].ToString() == ViewState["update"].ToString())
    {
        //=============== On click event code ========================= 

        lblDisplayAddedName.Text = txtName.Text;

        //=============== End of On click event code ==================

        // After the event/ method, again update the session 

        Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString()); 
    }
    else // If Page Refreshed
    {
        // Do nothing 
    }
}

protected override void OnPreRender(EventArgs e)
{
    ViewState["update"] = Session["update"];
 }

Get Last Running Query Based on SPID

Query 1-

To know which sessions are running currently, run the following command:
SELECT @@SPID
GO
get the latest run query in our input buffer
DBCC INPUTBUFFER(61)--61 is the output of above query
GO


Query 2- 

DECLARE @sqltext VARBINARY(128)
SELECT @sqltext = sql_handle
FROM sys.sysprocesses
WHERE spid = 61 -- get from
SELECT @@SPID 
SELECT TEXT
FROM
sys.dm_exec_sql_text(@sqltext)
GO
 
Please note that in any session there may be multiple running queries, but the buffer only saves the last query and that is what we will be able to retrieve.

Table Partitioning in SQL Server

  Table Partitioning in SQL Server – Step by Step Partitioning in SQL Server task is divided into four steps: Create a File Group Add Files ...