Wednesday, 13 November 2013

SQL Server Split Function Example in 2008 to Split Comma Separated String into Table

Introduction: 

Here I will explain simple split function in SQL Server to split comma separated string into table values inSQL Server database or How to split comma separated string with custom split() function in SQL Server. 

Description:


To split comma separated string in SQL Server we need to write custom method for that we need to create one function like as shown below

Custom Split function to split comma separated string into table


CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1))
RETURNS @Results TABLE (Items nvarchar(4000))
AS
BEGIN
DECLARE @INDEX INT
DECLARE @SLICE nvarchar(4000)
-- HAVE TO SET TO 1 SO IT DOESNT EQUAL Z
--     ERO FIRST TIME IN LOOP
SELECT @INDEX = 1
WHILE @INDEX !=0
BEGIN
-- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
SELECT @INDEX = CHARINDEX(@Delimiter,@STRING)
-- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
IF @INDEX !=0
SELECT @SLICE = LEFT(@STRING,@INDEX - 1)
ELSE
SELECT @SLICE = @STRING
-- PUT THE ITEM INTO THE RESULTS SET
INSERT INTO @Results(Items) VALUES(@SLICE)
-- CHOP THE ITEM REMOVED OFF THE MAIN STRING
SELECT @STRING = RIGHT(@STRING,LEN(@STRING) - @INDEX)
-- BREAK OUT IF WE ARE DONE
IF LEN(@STRING) = 0 BREAK
END
RETURN
END
Once we create custom function Split() run sample query like as shown below


SELECT items FROM [dbo].[Split] ('861,739,10,1670', ',') 
Once we run above query we will get output like as shown below

Output


Return unique values

Hi I have a text box that has values separated by a comma. I am trying to remove the duplicate values for, example this text box will have values like:
SO-001, SO-003, SO-002, SO-001, SO-001
To return unique values like:
SO-001, SO-003, SO-002
Use this Function it
public string RemoveDuplicates(string items)
 {
  StringBuilder Result = new StringBuilder();


  String[] newArray = items.Split(',');


  for (int i = 0; i < newArray.Length; i++)
  {
   if (Result.ToString().IndexOf(newArray[i]) == -1)
   {
    Result.Append(newArray[i].ToString()).Append(",");
   }
  }
  return Result.ToString().Substring(0, Result.ToString().LastIndexOf(','));
 }
To Call this Function Like this...
textbox1.Text=RemoveDuplicates(textbox1.Text);

Tuesday, 5 November 2013

Get financial year using C#

Get financial year using C# :

Like 13-14 instead of (2013-2014)

// The following C# function used to get the Financial year from the given date


       public static string GetFinancialYear(string cdate)
        {
            string finyear = "";
            DateTime dt = Convert.ToDateTime(cdate);
            int m = dt.Month;
            int y = dt.Year;
            if (m > 3)
            {
                finyear = y.ToString().Substring(2, 2) + "-" + Convert.ToString((y + 1)).Substring(2,2);   
                //get last  two digits (eg: 10 from 2010);
            }
            else
            {
                finyear = Convert.ToString((y - 1)).Substring(2, 2) + "-" + y.ToString().Substring(2, 2);
            }
            return finyear;
       }


 Like 13-14 instead of (2013-2014)


 public static string GetFinYear(string sdate)
        {
            string finyear = "";
            DateTime s = Convert.ToDateTime(sdate);

            int m = s.Month;
            int y = s.Year;
            if (m > 3)
            {
                finyear = y.ToString() + "-" + Convert.ToString((y + 1));
            }
            else
            {
                finyear = Convert.ToString((y - 1)) + "-" + y.ToString();
            }
            return finyear;

        }

Wednesday, 30 October 2013

How to Check Duplicate Item Names in Data Grid

void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (e.ColumnIndex == dataGridView1.Columns["MyCombo"].Index)
    {
        var query = from DataGridViewRow row in dataGridView1.Rows
                    where row.Cells[e.ColumnIndex].Value != null && row.Cells[e.ColumnIndex].Value.ToString() == e.FormattedValue.ToString()
                    where row.Index != e.RowIndex
                    select row;

        if (query.Any())
        {
            MessageBox.Show(string.Format("{0} already exists", e.FormattedValue.ToString()));
            e.Cancel = true;
        }
    }
}

Tuesday, 29 October 2013

Print Page margin Setup in RDLC Reports...

 PageSettings ps = new PageSettings(); //Declare a new PageSettings for printing
                    ps.Landscape = false; //Set True for landscape, False for Portrait
                    ps.Margins = new Margins(47, 43, 149, 1); //Set margins
                    //Choose paper size from the paper sizes defined in ur printer.
                    //Here we use Linq to quickly choose by name

                    ps.PaperSize =
                        (from PaperSize p
                        in ps.PrinterSettings.PaperSizes
                         where p.PaperName == "Legal"
                         select p).First();
                    //Alternatively you can set the paper size as custom
                    //ps.PaperSize = new PaperSize("MyPaperSize", 100, 100);

                    reportViewer1.SetPageSettings(ps);




Report Dynamic File name while saving into PDF/word/excel



this.reportViewer1.LocalReport.DisplayName = "Report Name";

Friday, 18 October 2013

SQL SERVER – Count Duplicate Records – Rows




SQL SERVER – Count Duplicate Records – Rows


In my previous article SQL SERVER – Delete Duplicate Records – Rows, we have seen how we can delete all the duplicate records in one simple query. In this article we will see how to find count of all the duplicate records in the table. Following query demonstrates usage of GROUP BY, HAVING, ORDER BY in one query and returns the results with duplicate column and its count in descending order.


SELECT YourColumn, COUNT(*) TotalCountFROM YourTable 
GROUP BY YourColumnHAVING COUNT(*) > 1 
ORDER BY COUNT(*) DESC

Saturday, 7 September 2013

Auto Complete Box


Auto Complete Box in WPF Application 

Design a page like below

<Label Content="Account : " FontWeight="Normal" Height="25" Margin="22,21,237,216" Name="Label6" />

<my:AutoCompleteBox  Grid.Column="0" HorizontalAlignment="Left" Margin="98,20,0,0" MinimumPrefixLength="2" FilterMode="Contains"  Name="txtLsname" VerticalAlignment="Top" Width="144" Height="25" ToolTip="Pick code" IsTabStop="True" />


Write the below code in Code behind

Private NameList As New List(Of String)()

Try
    NameList = objReadData.GetCompletionListACC("", 0, "")
    txtLsname.ItemsSource = NameList
    Catch ex As Exception
    System.Windows.MessageBox.Show("Could Not get AutoCompletion Details.")
End Try

 Public Function GetCompletionListACC(ByVal prefixText As String, ByVal count As Integer, ByVal contextKey1 As String) As Object
           
 Try
                SqlCommand command = new SqlCommand("SELECT AccountID, AccountName FROM Account;",connection);
SqlDataReader _dr= command.ExecuteReader();
                If IsDBNull(_dr) = False Then
                    If _dr.HasRows = True Then
                        While _dr.Read
                            c1 = _dr("AccountName").ToString.ToUpper.Trim
                            items.Add(c1)
                        End While
                    End If
                End If
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error")
            End Try
                        Return items
        End Function


Auto Complete Box in web Application (ASP.NET)


Design a page like below

 <td>
         <asp:Label ID="lblPartNo" runat="server" Text="Code" />                                                                    </td>
  <td>
 <div>
    <asp:TextBox ID="txtPartno" runat="server" CssClass="txtbx" Columns="20" MaxLength="7"
               Style="text-transform: uppercase" AutoPostBack="True" ToolTip="Enter the Part#"></asp:TextBox>
    <asp:AutoCompleteExtender runat="server" ID="autoComplete" TargetControlID="txtPartno"                      ServicePath="../CustomerAdminUser/AutoComplete.asmx" ServiceMethod="GetPartDetails"
              MinimumPrefixLength="2" CompletionInterval="10" EnableCaching="true" ContextKey="True"
  CompletionSetCount="5" CompletionListCssClass="AutoExtender" CompletionListItemCssClass="AutoExtenderList"
 CompletionListHighlightedItemCssClass="AutoExtenderHighlight" />                                                                            &nbsp;<span class="fontred">*</span>
</div>
</td>

Create a service method for Auto complete Box 

<WebMethod(EnableSession:=True)> _
    Public Function GetPartDetails(ByVal prefixText As String, ByVal count As Integer, ByVal contextKey As String) As String()
        Dim items As New List(Of String)
SqlConnection connection= new SqlConnection (";")
       SqlCommand command = new SqlCommand("SELECT AccountID, AccountName FROM Account;",connection);
      
 SqlDataReader _dr = command.ExecuteReader();
        Try
           
            If IsDBNull(_dr) = False Then
                If _dr.HasRows = True Then
                    While _dr.Read
                        items.Add(_dr("AccountName ").ToString.ToUpper.Trim)
                    End While
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error")
        End Try
        If connection.State = ConnectionState.Open Then connection.Close()
        Return items.ToArray()

    End Function

SQL SERVER – Disk Space Monitoring – Detecting Low Disk Space on Server

CREATE PROCEDURE [CSMSDVLP].[DiskSpaceMonitor] @mailProfile nvarchar(500), @mailto nvarchar(4000), @threshold INT, @logfile nvarchar(40...