Thursday, June 14, 2012

How to exchange the two word of one column data using sql.

Introduction:
                     Here I am going to discussion about how to exchange the word of one column data using sql.

Some days back i had one Problem arise where i need to exchange the word of column data.In actual seniorio is like this ...In one table Users one column name Full Name is there where "FirstName LastName" stored but while displaying data I have to display "LastName FirstName".In this seniorio i have to apply the below querry to get the results.

The Users Table is Like this.



Now Apply below Querry.

Select SUBSTRING(FullName,CHARINDEX(' ',FullName)+1,50) + ' ' + SUBSTRING(FullName,0,CHARINDEX(' ',FullName,0)) as "LastName-FirstName" from  Users

Here i used the Substring where first substring will fetch the second word(LastName) and the second substring will fetch the first word(FirstName) and then i have concat it  both and name the column name "LastName-FirstName".

SUBSTRING(FullName,CHARINDEX(' ',FullName)+1,50)=CHARINDEX(' ',FullName) will find the string after space.means second word to end of string

CHARINDEX(' ',FullName,0)=this one string will start from index 0 to space will found means First word


The Output will be 


Thursday, June 7, 2012

FileUpload Progress bar using Ajax

Introduction:
                  I explained in my Previous Post about AjaxMaskEdit  in http://www.aspdotnetbank-kartik.blogspot.in/2012/02/ajax-maskedit-for-date-validator.html.Now in this Post I am going to explain you about Progress bar using Ajax AsyncFileUpload while FileUpload.

I am Going to show how to use Progressbar while Uploading the File.Here I am Going To Upload file Using FileUpload and while Uploading the File It will show you the Progress bar.First You have to add the AjaxtToolkit as a Reference.and also add the Images Folder inside Project.

Lets Look at .aspx code

Add above <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>

<head runat="server">
    <title>Example Of Progressbar</title>
    <script type="text/javascript">
        // This function will execute after file uploaded successfully
        function uploadComplete() {

            document.getElementById('<%=lblMsg.ClientID %>').innerHTML = "File Uploaded Successfully";
        }
        // This function will execute if file upload fails
        function uploadError() {
            document.getElementById('<%=lblMsg.ClientID %>').innerHTML = "File upload Failed.";
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <ajax:ToolkitScriptManager ID="scriptManager1" runat="server"/>
        <ajax:AsyncFileUpload ID="fileUpload1" OnClientUploadComplete="uploadComplete" OnClientUploadError="uploadError"
            CompleteBackColor="White" Width="350px" runat="server" UploaderStyle="Traditional"
            UploadingBackColor="#CCFFFF" ThrobberID="imgLoad" OnUploadedComplete="fileUploadComplete" />
        <br />
        <asp:Image ID="imgLoad" runat="server" ImageUrl="loading.gif" />
        <br />
        <asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>

If you Look at above code UploaderStyle="Traditional" in that there are two option "Morden" and "Traditional" both have different Look for FileUploader.Here i have used Traditional.while OnUploadedComplete="fileUploadComplete" specify the Method for Uploading code in aspx.cs Page.

Now Lets Look at aspx.cs Page code : You have to just the Method fileUploadComplete in aspx.cs page.


using System.Threading;
using AjaxControlToolkit;

 protected void fileUploadComplete(object sender, AsyncFileUploadEventArgs e)
 {
            Thread.Sleep(5000);
            string filename = System.IO.Path.GetFileName(fileUpload1.FileName);
            fileUpload1.SaveAs(Server.MapPath("Images/") + filename);
  }
Here I have used Thread.Sleep Method Because If you are Going to Upload the small file then also you can see the Progress bar.Thread.Sleep(5000) will suspend the execution of code for 5 second.


Note:If your aspx Page uses any master page then specify the attribute ClientIDMode="AutoID" in <ajax:AsyncFileUpload ....> Tag


Demo:
Download the Sample Code from Here
 Download



Wednesday, June 6, 2012

Returning ID from insert query in C#

Intoduction:
         I am going to explain how to return the Id after Inserting the data into table.

There may be many occassion comes where you need to use the Id of data after inserting the values into table.If you look at my post Explained in http://aspdotnetbank-kartik.blogspot.in/2012/05/how-to-create-webservice-and-how-can-we.html there is one Table called Office in that Post.so first you Create a Table(Office)  from that Post.but Be Remeber that OfficeId is Primary Key and also Auto Increment Value.

Now Lets Look at .aspx page

<form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    <asp:Label ID="lblOfficeName" runat="server" Text="Office Name"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtOfficeName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lblCity" runat="server" Text="City"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lblCountry" runat="server" Text="Country"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
                    <asp:Label ID="lblId" Text="ID=" runat="server"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    </form>

Now .aspx.cs Page write code in button Save Click Event.

  protected void btnSave_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"Data Source=GTL--7\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
            con.Open();
            string s = "insert into Office values('" + txtOfficeName.Text + "','" + txtCity.Text + "','" + txtCountry.Text + "')";
            SqlCommand cmd = new SqlCommand(s, con);
            cmd.ExecuteNonQuery();
            SqlCommand idCMD = new SqlCommand("SELECT SCOPE_IDENTITY(); ", con);
            // Retrieve the identity value and store it in the CategoryID column.
            int newID = Convert.ToInt16(idCMD.ExecuteScalar());
            lblId.Text += newID;
        }

Now If you Look at the code I have used SqlCommand idCMD = new SqlCommand("SELECT SCOPE_IDENTITY(); ", con); It Just returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value.


You can also use the Select Ident_Current(TableName);  and SELECT @@IDENTITY; in Place Of  SELECT SCOPE_IDENTITY();  from above example.

Means There are three way we can achieve the Id.Lets disccuss about this

Select Ident_Current(TableName);  For ex. Select Ident_Current('Office');

SELECT @@IDENTITY;

SELECT SCOPE_IDENTITY();

SELECT @@IDENTITY It returns the last IDENTITY value produced on a connection, regardless of the table that produced the value, and regardless of the scope of the statement that produced the value. @@IDENTITY will return the last identity value entered into a table in your current session. While @@IDENTITY is limited to the current session, it is not limited to the current scope. If you have a trigger on a table that causes an identity to be created in another table, you will get the identity that was created last, even if it was the trigger that created it.

SELECT SCOPE_IDENTITY() It returns the last IDENTITY value produced on a connection and by a statement in the same scope, regardless of the table that produced the value. SCOPE_IDENTITY(), like @@IDENTITY, will return the last identity value created in the current session, but it will also limit it to your current scope as well. In other words, it will return the last identity value that you explicitly created, rather than any identity that was created by a trigger or a user defined function.

SELECT IDENT_CURRENT(‘tablename’) It returns the last IDENTITY value produced in a table, regardless of the connection that created the value, and regardless of the scope of the statement that produced the value. IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope.

Download Source Code from here
Download

Now If you are using Linq to insert the Data then Its really Easy....

Office record = new Office();
record.OfficeName = "KP";
record.City="Ahmedabad";
record.Country="India";
db.MyTable.InsertOnSubmit(record);
db.SubmitChanges();
lblId.Text +=record.OfficeId

Monday, June 4, 2012

How do I find a value anywhere in a SQL Server Database?

Introduction

           This is really nice stuff and will get the useful at any time to anybody.I was at this situation where I want to find particular data but i dont know where this data reside means in which Table and in which column this data was there.At that Time i got this solution.I hope that it might help you.


I am posting on SP in which it searches all the columns of all tables in a given database and then Find the Particular Data.


 ALTER PROC [dbo].[SearchAllTables]
(
    @SearchText nvarchar(100)
)
AS
BEGIN

-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT

DECLARE @Results TABLE(ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchText2 nvarchar(110)
SET  @TableName = ''
SET @SearchText2 = QUOTENAME('%' + @SearchText + '%','''')

WHILE @TableName IS NOT NULL
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM    INFORMATION_SCHEMA.COLUMNS
            WHERE       TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND TABLE_NAME  = PARSENAME(@TableName, 1)
                AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND QUOTENAME(COLUMN_NAME) > @ColumnName
        )

        IF @ColumnName IS NOT NULL
        BEGIN
            INSERT INTO @Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchText2
            )
        END
    END 
END

SELECT ColumnName, ColumnValue FROM @Results
END