Update Table using JOIN in SQL Server

Update a table value from another Table using JOIN Query in SQL Server

Code :
    UPDATE
        A
    SET
        A.Colx = B.Coly
    FROM
        Table1 A
    JOIN
        Table2 B ON A.col1 = B.col5
    WHERE
        A.Col3 = 'xyz'

Convert Text to XML Data in SQL Server.

Convert Text to XML Data in SQL Server.

In the following Stored Procedure we can Use XML Data as Follows.
Send XML Data to Stored Procedure as "Text" Data Type.
In SP Convert this "Text" (XML Text)  to "XML" Data
Read and Fetch the XML Data into Table.
Use the Cursor to Traverse through Data.

Code :
/**************************************************************************
 
-----------------------  
Developers Note   
-----------------------  
Object          : StoredProcedure [dbo].[canon_UpdateValidUserFromXML]      
Script Date     : 19/11/2012   
Developed By    : Rohit Shram  
Used For        : Update Valid  Users 
Implementaion   :   
    SELECT *  FROM [USER] where ID in ( 80309 ,80310)
    GO
    UpdateValidUserFromXML
    '<UsersList>
        <Users>
            <ID>80309</ID>
            <UserName>KARL TYLER</UserName>
            <Email>CRAIG.WASHINGTON80309@testmail.com</Email>
        </Users>
        <Users>
            <ID>80310</ID>
            <UserName>CHAD MARTIN</UserName>
            <Email>LEWIS.CUNNINGHAM80310@testmail.com</Email>
        </Users>
    </UsersList>',
    'File1234',
    80311
    GO
    SELECT *  FROM [USER] where ID in ( 80309 ,80310)

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

CREATE PROCEDURE [dbo].[UpdateValidUserFromXML] 

    @UsersXml TEXT  
--'<UsersList><Users><ID>12</ID><UserName>KAYR</UserName><Email>CRAI@test.com</Email></Users></UsersList>' 
AS  
BEGIN  
    SET NOCOUNT ON;  
    
    BEGIN TRANSACTION Update
    
    BEGIN TRY
    
    DECLARE @idoc INT
    DECLARE @ID INT                  
    DECLARE @UserName NVARCHAR(500)                
    DECLARE @Email NVARCHAR(500)                
 
    -- Used to Keep ErrorList for all Users Data as Table
    DECLARE @UsersErrorList TABLE                  
    (                  
        ID INT,                 
        Name NVARCHAR(500),                
        Email NVARCHAR(500),                 
        Error NVARCHAR(MAX)       
    ) 
 
    -- Used to Keep XML Data as Table
    DECLARE @UsersList TABLE                  
    (                  
        ID INT,                 
        UserName NVARCHAR(500),                
        Email NVARCHAR(500)                
    ) 

    -- Prepare XML Doc
    EXEC sp_xml_preparedocument @idoc OUTPUT, @UsersXml                  
          
    -- Insert into Table Variable From XML
    INSERT @UsersList                
    (                 
        ID,                
        UserName,                 
        Email                
    )                  
    SELECT                   
        ID,                
        UserName,                 
        Email               
       
    FROM                  
    OPENXML (@idoc, '/UsersList/Users')                  
    WITH                 
    (                  
        ID INT 'ID',                 
        UserName NVARCHAR(500) 'UserName',                
        Email NVARCHAR(500) 'Email'               
    )                  
           
    -- Remove XML Do after getting Data
    EXEC sp_xml_removedocument @idoc           
   
    -- Declare Cursor
    DECLARE Cursor CURSOR FOR                  
    SELECT                  
    ID,                
    UserName,                 
    Email                
    FROM @UsersList                   
         
    -- Open Cursor
    OPEN Cursor                  
         
    -- Fetch Cursor
    FETCH NEXT FROM Cursor INTO                   
    @ID,                  
    @UserName,                  
    @Email       
         
    -- Traverse through Data                
    WHILE @@FETCH_STATUS = 0                
    BEGIN  
  
        -- Update User's Name and Email    
        UPDATE [USER] 
        SET Email = @Email, UserName = @UserName 
        WHERE ID = @ID 
  
        -- Fetch Cursor
        FETCH NEXT FROM Cursor INTO                   
        @ID,                  
        @UserName,                  
        @Email                 
                  
    END  -- WHILE @@FETCH_STATUS = 0                
                 
        CLOSE Cursor                  
        DEALLOCATE Cursor 
 
    END TRY
    BEGIN CATCH

        -- Rollback Transaction If any Transaction Occured
        IF @@ROWCOUNT > 0
            ROLLBACK TRANSACTION Update
  
        -- Insert Into Temp table to Keep Error Details for all Users
        INSERT INTO @UsersErrorList
        VALUES ( @ID , @UserName , @Email , ERROR_MESSAGE())

    END CATCH
 
    -- Returns Error ResultSet
    SELECT * FROM @UsersErrorList;  

    -- Commit Transaction If any Transaction Occured
    IF @@TRANCOUNT > 0
        COMMIT TRANSACTION Update
    
    SET NOCOUNT OFF;  

END  
   

Use Try...Catch Block and Transactions in SQL Server

Use Try...Catch Block and Transactions in Stored Procedure as Followes :

Code :
/******************************************************************************    
-----------------------  
Developers Note   
-----------------------  
Object          : StoredProcedure [dbo].[sp_SetUsersDetails]     
Script Date     : 19/11/2012   
Developed By    : Rohan Sharma
Used For        : Add/Update User
Implementaion   :   

    sp_SetUsersDetails 5, 'Rohan Sharma', 'Block-B', '87867675765'

*****************************************************************************/ 
 
CREATE PROCEDURE [dbo].[sp_SetUsersDetails] 
    -- Parameters Here
    @ID   INT, 
    @Name  NVARCHAR(500), 
    @Address NVARCHAR(500) = NULL, 
    @Phone  NVARCHAR(500) = NULL, 
AS  
BEGIN  

    SET NOCOUNT ON;  

    BEGIN TRANSACTION UpdateLMS

    BEGIN TRY

        -- Put Your Tansaction DB Codes Here

    END TRY
    BEGIN CATCH

        -- Rollback Transaction If any Transaction Occured
        IF @@ROWCOUNT > 0
            ROLLBACK TRANSACTION UpdateLMS

        -- Put Any ErrorLog Codes Here

    END CATCH

    -- Commit Transaction If any Transaction Occured

    IF @@TRANCOUNT > 0
        COMMIT TRANSACTION UpdateLMS

    SET NOCOUNT OFF;  

END  
   

Export Data From Excel File in ASP.Net

Export Data From Excel File in ASP.Net

The following function takes the following parameter :

    "excelFileName" : Its specify the Path with File Name .i.e: "D:\MyExcel.xls"

Use the following NameSpace :
    using System.IO;
    using System.Reflection;
    using Microsoft.Office.Interop.Excel;
Code :
    /// <summary>
    /// This function convert uploaded Ecxcel sheet into DataTable and then returns 
    /// </summary>
    /// <param name="fileToConvert"></param>
    /// <param name="fileForDs"></param>
    /// <param name="uniqueFileName"></param>
    /// <returns></returns>
    public System.Data.DataTable ReadFromExcelFile(string excelFileName)
    {
        OleDbConnection connection = null;

        //this datatable contains Active Sheet  records 
        System.Data.DataTable dtImprtExcel = new System.Data.DataTable();

        try
        {

            // Get Active Sheet Name
            string activeSheetName = getActiveSheetName(excelFileName);

            //If Active Sheet Name is not Null or Blank
            if (!string.IsNullOrEmpty(activeSheetName))
            {

                // <add key="ExcelConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Path;Extended Properties=Excel 8.0;"/>
                string connectionString = ConfigurationManager.AppSettings.Get("ExcelConnectionString").Replace("Path", excelFileName);
                OleDbConnection excelCon = new OleDbConnection(connectionString);
                excelCon.Open();
                OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + activeSheetName + "$]", excelCon);
                adapter.Fill(dtImprtExcel);
                excelCon.Close();

                //cleans up the temporary file that was stored
                File.Delete(excelFileName);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (connection != null)
            {
                if (connection.State == ConnectionState.Open)
                {
                    //close a open connection
                    connection.Close();
                }
            }
        }
        return dtImprtExcel;
    }

Get Active Sheet Name :

The following function takes the following parameter :
"strFileName" : Its specify the Path with File Name .i.e: "D:\MyExcel.xls"

Use the following NameSpace :

    using System.IO;
    using System.Reflection;
    using Microsoft.Office.Interop.Excel;

Code :

    /// <summary>
    /// Get Excel Sheet Name
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    private string getActiveSheetName(string strFileName)
    {
        string activeSheetName = string.Empty;
        try
        {
            Application oXL;
            Workbook oWB;
            Worksheet oSheet;

            // Start Excel and get Application object. 
            oXL = new Application();

            // Set some properties 
            oXL.Visible = false;
            oXL.DisplayAlerts = false;

            // Open the workbook. 
            oWB = oXL.Workbooks.Open(strFileName);

            // Get the active sheet 
            oSheet = (Worksheet)oWB.ActiveSheet;
            activeSheetName = oSheet.Name;

            // Save the sheet and close 
            oSheet = null;
            oWB.SaveAs(strFileName, Excel.XlFileFormat.xlWorkbookNormal,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                XlSaveAsAccessMode.xlExclusive,
                Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);
            oWB.Close(Missing.Value, Missing.Value, Missing.Value);
            oWB = null;
            oXL.Quit();

            // Clean up 
            // NOTE: When in release mode, this does the trick 
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return activeSheetName;
    }

Get ActiveSheet Name of Uploaded Execl in ASP.Net

 The following function takes the following parameter :

    "strFileName" : Its specify the Path with File Name .i.e: "D:\MyExcel.xls"

Use the following NameSpace :
    using System.IO;
    using System.Reflection;
    using Microsoft.Office.Interop.Excel;
Code :
    /// <summary>
    /// Get Excel Sheet Name
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    private string getActiveSheetName(string strFileName)
    {
        string activeSheetName = string.Empty;
        try
        {
            Application oXL;
            Workbook oWB;
            Worksheet oSheet;

            // Start Excel and get Application object. 
            oXL = new Application();

            // Set some properties 
            oXL.Visible = false;
            oXL.DisplayAlerts = false;

            // Open the workbook. 
            oWB = oXL.Workbooks.Open(strFileName);

            // Get the active sheet 
            oSheet = (Worksheet)oWB.ActiveSheet;
            activeSheetName = oSheet.Name;

            // Save the sheet and close 
            oSheet = null;
            oWB.SaveAs(strFileName, Excel.XlFileFormat.xlWorkbookNormal,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                XlSaveAsAccessMode.xlExclusive,
                Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);
            oWB.Close(Missing.Value, Missing.Value, Missing.Value);
            oWB = null;
            oXL.Quit();

            // Clean up 
            // NOTE: When in release mode, this does the trick 
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return activeSheetName;
    }

Download Excel in ASP.Net

The Following Function downloads the Excel .

It accepts the following paramete :
fileName : It contains the path with FileName . I.e : "D:\MyExcel.exe".

Code :
    /// <summary>
    /// Download Excel template with some existing data
    /// </summary>
    /// <param name="fileName"></param>
    private void DownloadExcel(string fileName)
    {
        try
        {
            FileInfo file = new FileInfo(fileName);
            if (file.Exists)
            {
                // Clear the content of the response
                Response.ClearContent();
                Response.Clear();

                // add the header that specifies the default filename for the Download/SaveAs dialog
                Response.AddHeader("Content-Disposition", "attachment; filename=LMSUsers.xls");

                // add the header that specifies the file size, so that the browser can show the download progress
                Response.AddHeader("Content-Length", file.Length.ToString());

                // specify that the response is a stream that cannot be read by the client and must be downloaded
                Response.ContentType = "application/vnd.ms-excel";

                // send the file stream to the client
                Response.WriteFile(file.FullName);
                Response.BufferOutput = true;
                Response.Flush();
                Response.Close();

                //Delete the file if Required
                file.Delete();
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.InnerException.Message);
        }
    }

Create Excel with Data in ASP.Net

Create Excel in ASP.Net with Dynamic data .

The following function takes the following parameter :
    "DataTable"  : which holds the data from Database.
    "strFileName" : It is specify the Path with File Name .i.e: "D:\MyExcel.xls"
 
Use the following NameSpace :
    using System.IO;
    using System.Reflection;
    using Microsoft.Office.Interop.Excel;
Code :
    /// <summary>
    /// Creates the excel file from the provided dataset.
    /// </summary>
    /// <param name="dtSource">The dt source.</param>
    /// <param name="strFileName">Name of the STR file.</param>
    private void GenerateExcel(System.Data.DataTable dtSource, string strFileName)
    {
        Application oXL;
        Workbook oWB;
        Worksheet oSheet;
        Range oRange;

        // Start Excel and get Application object. 
        oXL = new Application();

        // Set some properties 
        oXL.Visible = false;
        oXL.DisplayAlerts = false;

        // Get a new workbook. 
        oWB = oXL.Workbooks.Add(Missing.Value);

        // Get the active sheet 
        oSheet = (Worksheet)oWB.ActiveSheet;
        oSheet.Name = "LMS Users";
        int rowCount = 1;

        // Add Headrer to Excel
        for (int i = 1; i < dtSource.Columns.Count + 1; i++)
        {
            oSheet.Cells[1, i] = dtSource.Columns[i - 1].ColumnName;
            oRange = (Microsoft.Office.Interop.Excel.Range)oSheet.Cells[1, i];
            oRange.Font.Bold = true;
        }

        // Add the Data Rows to the Excel
        if (dtSource.Rows.Count > 0)
        {
            foreach (DataRow dr in dtSource.Rows)
            {
                rowCount += 1;
                for (int i = 1; i < dtSource.Columns.Count + 1; i++)
                {
                    if (rowCount > 1)
                    {
                        oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
                    }
                }
            }
        }
        
        // Resize the columns 
        oRange = oSheet.get_Range(oSheet.Cells[1, 1],
                      oSheet.Cells[rowCount, dtSource.Columns.Count]);
        oRange.EntireColumn.AutoFit();

        // Save the sheet and close 
        oSheet = null;
        oRange = null;
        oWB.SaveAs(strFileName, Excel.XlFileFormat.xlWorkbookNormal,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            XlSaveAsAccessMode.xlExclusive,
            Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value);
        oWB.Close(Missing.Value, Missing.Value, Missing.Value);
        oWB = null;
        oXL.Quit();

        // Clean up 
        // NOTE: When in release mode, this does the trick 
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
    }

How to get File and Function Details from Exception object

Its better to use ErrorLog in Exception Handling. In ErrorLog we need to keep track of the File and the Function details where this Exception occurs. So, instead of sending the Hardcoded Values (i.e : Function Name , File Name ) to ErrorLog, we can directly get this details from Exception object (i.e : Exception ex) as follows :

Code :

Use namespace :
using System.Diagnostics;
using System.Reflection;
Function where Error Occurred :

        /// <summary>
        /// Set AssetName for the AssetID
        /// </summary>
        /// <param name="programId"></param>
        /// <param name="languageId"></param>
        /// <param name="assetId"></param>
        /// <param name="assetName"></param>
        public void SetAssetName(Int32 progId, Int32 langId, int astId, string astName)
        {
            AssetClient assetClient = null;
            try
            {
                assetClient = new AssetClient(appBindingAssets);
                //return assetClient.SetAssetName(progmId, langId, astId, astName);
            }
            catch (Exception ex)
            {
                //call ErrorLog using the File Details
                LogError(ex);
            }
            finally
            {
                if (assetClient != null)
                {
                    assetClient.Close();
                }
            }
        }
ErrorLog Function accepts Exception object as Parameter :
        /// <summary>
        /// Logs the exception. 
        /// </summary>
        /// <param name="ex"></param>
        public static void LogError(Exception ex)
        {
            // Get the File Details from Exception
            StackTrace st = new StackTrace(ex);
 
            // Get the object of MethodBase from StackTrace
            MethodBase mb = st.GetFrame(st.FrameCount - 1).GetMethod();
 
            // Get FileName with NameSpace 
            // Ex: IGroup.Modules.SalesZone.Controller.SalesZoneController"
            string source = mb.DeclaringType.FullName;
 
            // Get Function Name "GetPhraseTranslationList"
            string methodName = mb.Name;
 
            //Implement ErrorLog Logics here using the File Details
            //AddLogError(source, ex, methodName);
        }

Bind same event to Multiple controls in JQuery

When multiple controls needs to fire a same event.
Instead of binding the event to each control separately , we can create an array of controls and loop through it to bind the single event as following :

Code :

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Single Event for Multiple Controls</title>
     <script src="http://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function() {
                var btns = $('#btnA,#btnC,#btnE');
                $.each(btns, function() {
                    $(this).click(function() {
                        alert(this.id);
                    });
                });
            });
        </script>
</head

<body>
    <input id="btnA" type="button" value="Button A" />
    <input id="btnB" type="button" value="Button B" />
    <input id="btnC" type="button" value="Button C" />
    <input id="btnD" type="button" value="Button D" />
    <input id="btnE" type="button" value="Button E" />
</body>
</html>

Optimize IIS Performance using "Enable Gzip compression"

Enable Gzip compression :

Enable Gzip compression is one of the Feature to Optimize IIS and enhances the performance of sites and applications.
This feature allows user to use bandwidth more effectively and efficiently by using common compression mechanisms such as Gzip and Deflate.
It provides options to Configure HTTP Compression for both static and dynamic sites.
It is supported by Windows 7, Windows Server 2008, Windows Server 2008 R2, Windows Vista

How it works ?

Lets discussion how exactly the application works with out Compression and with Compression

Process with out Compression :

When you request a file like http://www.KnowledgeParlour.com/Default.html, your browser communicates to a web server as follows :

1. Browser sends request to get Default.html to Server.
2. Server checks if Default.html is available or not .
3. Server if Found Default.html then sends back the response code and the file.
4. Browser received the file which is around let 500KB, which is very slow . Then loads the file .

Process with Compression :

If the browser gets a .zip file (i.e. Default.html.zip) instead of normal Default.html , then it can save bandwidth and download time. Then The browser can download the zipped file, extract it, and then show it to user. Which is bit faster.
So using "Enable Gzip Compression" we can archieve the above process as follows :

1. Browser sends request to get Default.html to Server and informs to get the Compressed version of the response file.
2. Server checks if Default.html is available or not .
3. Server if Found Default.html then it Zip the file sends back the response code and the zipped File.
4. Browser received the Zipped file which is around 50KB , which is bit Faster and enhance the performance of application . Then it unzip the file and loads it .

Reason behind it :

When browser received the file from Server if it is smaller then it takes less time to download and process. so using Gzip Compression server makes the file let 500KB to 50KB which enhance the Performance and makes the application runs faster

How to configure compression ?

1. Open IIS Manager and navigate to the level you want to manage.
2. In Features View, double-click Compression.
3. Choose one or both of the following:
   a. Enable dynamic content compression to configure IIS to compress dynamic content.
   b. Enable static content compression to configure IIS to compress static content.
4. Click Apply in the Actions pane.

web.config Changes :

Once its applied , the following code has been updated in web.config file
<system.webServer> 
        <urlCompression doDynamicCompression="true" />
</system.webServer>

Take Backup with Data of single Table in SQL Server

Create Backup table Instantly :

The Following query automatically creates a Table with name "Table_Backup" and Insert all the rows of "Table_Old" into "Table_Backup"

Example :
    SELECT *  INTO  Table_Backup FROM Table_Old

External Style Sheets

Introduction :

External style sheets have many powerful that make them ubiquitous in professional Web sites:

  • It keeps your website design and content separate.
  • It's much easier to reuse your CSS code if you have it in a separate file. Instead of typing the same CSS code on every web page you have, simply have many pages refer to a single CSS file with the "link" tag.
  • You can make drastic changes to your web pages with just a few changes in a single CSS file.
  • It allows a single style sheet to control the rendering of multiple documents.
  • This results in a time-savings for the author, a savings of space for the web server, and less download time for the user.
  • This method can be used in both HTML and XML.
  • In Application When using CSS it is preferable to keep the CSS separate from your HTML.
  • Placing CSS in a separate file allows the web designer to completely differentiate between content (HTML) and design(CSS).

An External Style Sheet is a file containing only CSS syntax and should carry a MIME type of "text/css."
It is saved with a ".css" filename extensions that file is then referenced in your HTML using the "link" instead of "style".
By using the Link Tag to load a basic external style sheet (CSS), it's possible to control the look n feel of multiply WebPages by making changes to One style sheet.
This means that it is easy to change font, bgcolor, background, etc on ALL pages - just by changing one external style sheet (CSS).

Those CSS files define page attributes for every page to which they are linked.
The style information is not explicitly tied directly to the document's elements, so Selector syntax is used to specify what styles attach to which portions of the document tree.
The full range of CSS syntax is allowed in this method.

Example with codes :

The 'link' is always added to the Head Section i.e anywhere between the "head" and the "/head"

HTML Code:
    link rel="stylesheet" type="text/css" href="style.css"

Just create a text (ASCII) file named (test.css) that contains the code shown below.
Put the style.css file in the same folder / directory as the file .

Let us create an external CSS file. Open up notepad.exe, or any other plain text editor and type the following CSS code.

CSS Code:
    body
    {
        background-color: #FFFFF0;
        font-family: Arial, Verdana, sans-serif;
        font-size: 18px;
        color: #00008B;
    }

    a
    {
        font-family: Arial, Verdana, sans-serif;
        font-size: 18px;
        color: Blue;
        text-decoration: underline;
    }

    a:hover
    {
        font-family: Arial, Verdana, sans-serif;
        font-size: 18px;
        color: Red;
        background-color: Green;
    }

    h1 
    { 
        font-family: Arial, Verdana, sans-serif; 
        font-size: 32px; 
        color: blue; 
    }

    table
    {
        font-family: Arial, Verdana, sans-serif;
        font-size: 18px;
        color: #00008B;
        margin-top: 0px;
        margin-right: 0px;
        margin-bottom: 0px;
        margin-left: 0px;
        padding-top: 0px;
        padding-right: 0px;
        padding-bottom: 0px;
        padding-left: 0px;
    }

Now save the file as a CSS (test.css) file.
Now create a new HTML file and fill it with the following code.

HTML Code:
    link rel="stylesheet" type="text/css" href="test.css"

Then save this file as "Sample.html" (without the quotes) in the same directory as your CSS file.

Now open your HTML file in your web browser and it should look something like this..

Display:

A Blue Header

Image link in Blue Colour. then on Mouse hover it will be red colur with green background because we changed it with CSS!

Advantages :

External style sheets have many powerful that make them ubiquitous in professional Web sites:
  • It keeps your website design and content separate.
  • It's much easier to reuse your CSS code if you have it in a separate file. Instead of typing the same CSS code on every web page you have, simply have many pages refer to a single CSS file with the "link" tag.
  • You can make drastic changes to your web pages with just a few changes in a single CSS file.
  • It allows a single style sheet to control the rendering of multiple documents.This results in a time-savings for the author, a savings of space for the web server, and less download time for the user.
  • This method can be used in both HTML and XML.

SET Vs. SELECT in SQL Server

Introduction

SET and SELECT both key words are used to Assign Variables in SQL Server.

SET and SELECT both specifies the columns to be changed and the new values for the columns.
The values in the specified columns are updated with the values specified in the SET and SELECT in all rows that match the WHERE clause search condition.
If no WHERE clause is specified, all rows are updated.

There are some difference based on the Performance, Process like Follows :

1. SET is the ANSI standard for variable assignment, SELECT is not.
2. SELECT can be used to assign values to more than one variable at a time, Whereas SET allows to assign data to only one variable at a time.

Example :
    /* Declaring variables */
    DECLARE @Var1 AS int, @Var2 AS int

    /* The same can be done using SET, but two SET statements are needed */
    SET @Var1 = 1
    SET @Var2 = 2

    /* Initializing two variables at once */
    SELECT @Var1 = 1, @Var2 = 2

But use SET instead SELECT, for variable initialization, It will throw the following error

Example :
    SET @Var1 = 1, @Var2 = 2

    Msg 102, Level 15, State 1, Line 10
    Incorrect syntax near ','.

3. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all .so the variable will not be changed from it's previous value.

Example :

Run it in master Database in SQL Server.
    /* Returns NULL */
    DECLARE @Title varchar(80)
    --SET @Title = 'Not Found'

    SET @Title =
    (
    SELECT error
    FROM SysMessages
    WHERE Description = 'Invalid Description'
    )

    SELECT @Title
    GO

    /* Returns the string literal 'Not Found' */
    DECLARE @Title varchar(80)
    SET @Title = 'Not Found'

    SELECT @Title = error
    FROM SysMessages
    WHERE Description = 'Invalid Description'

    SELECT @Title
    GO

4. Let using a query needs to populate a variable and the Query returns more than one value.
SET will fail with an error in this scenario.
But SELECT will assign one of the returned rows and mask the fact that the query returned more than one row.

As a result, bugs in your the could go unnoticed with SELECT, and this type of bugs is hard to track down too.

Example :
    /* Consider the following table with two rows */
    SET NOCOUNT ON
    CREATE TABLE #Table (i int, j varchar(10))
    INSERT INTO #Table (i, j) VALUES (1, 'Sunday')
    INSERT INTO #Table (i, j) VALUES (1, 'Monday')
    GO

    /* Following SELECT will return two rows, but the variable gets its value from one of those rows, without an error.
    you will never know that two rows existed for the condition, WHERE i = 1 */
    DECLARE @j varchar(10)
    SELECT @j = j FROM #Table WHERE i = 1
    SELECT @j
    GO

    /* If you rewrite the same query, but use SET instead, for variable initialization, you will see the following error */
    DECLARE @j varchar(10)
    SET @j = (SELECT j FROM #Table WHERE i = 1)
    SELECT @j

    Msg 512, Level 16, State 1, Line 4
    Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, &lt;, &lt;= , >, >= or when the subquery is used as an expression.

Based on the above results, when using a query to populate variables, we should always use SET.
If you want to be sure that only one row is returned then only use SELECT, as shown below:

Example :
    DECLARE @j varchar(10)
    SELECT @j = (SELECT j FROM #Table WHERE i = 1)
    SELECT @j

5. This very feature of SELECT makes it a winner over SET, when assigning values to multiple variables. A single SELECT statement assigning values to 3 different variables, is much faster than 3 different SET statements assigning values to 3 different variables.
In this scenario, using a SELECT is at least twice as fast, compared to SET.

So, the conclusion is, if there is a loop in th stored procedure that manipulates the values of several variables, and if you want to squeeze as much performance as possible out of this loop, then do all variable manipulations in one single SELECT statement or group the related variables into few SELECT statements as show below:

Example :
    SELECT @Var1 = @Var1 + 1, @Var2 = @Var2 - 1, @CNT = @CNT + 1