Split String
Hi friends ,
In my database i have a column named "Name" in this column i had stored firstname and lastname with '_' seprator. Ex : "XYZ_ABC".
But now in my select query i would like to have only lastname to fetch.
For that what should i do? How to splite the value in select query ?
Waiting for the reply.
Thank you.
Lalit MRank #1,186 · 1.5K reputationPosted Dec 13, 2009, 10:10 PM EST
class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public void NameSplit(string name)
reference link{
if(name.Length > 0)
{
// Check for a comma
if(name.IndexOf(",") > 0)
{
LastName = name.Substring(0, name.IndexOf(",")).Trim();
FirstName = name.Substring(name.IndexOf(",") + 1).Trim();
}
else if(name.IndexOf(" ") > 0)
{
FirstName = name.Substring(0, name.IndexOf(" ")).Trim();
LastName = name.Substring(name.IndexOf(" ") + 1).Trim();
}
}
}
}
Srinivas KotraRank #8,059 · 229 reputationPosted Dec 13, 2009, 10:21 PM EST
Kirtan PatelRank #292 · 8.6K reputationPosted Dec 14, 2009, 1:39 AM EST
Friend,
You can Do this By two Ways By using SQL Server in which you have to construct your own function in database or you can do it Code Behind Side.
I have Shown you Second Way here because it easiest to understand ...
private void button1_Click(object sender, EventArgs e)
{
List<string> LastNames = new List<string>();
SqlConnection con = new SqlConnection("your connection string");
con.Open();
SqlCommand comm = new SqlCommand("select name from students", con);
SqlDataReader reader = comm.ExecuteReader();
LastNames.Clear();
while (reader.Read())
{
string[] name = reader[0].ToString().Split('_');
LastNames.Add(name[0]);
}
dataGridView1.DataSource = LastNames;
con.Close();
}
Hiren SoniRank #694 · 3.5K reputationPosted Dec 14, 2009, 1:46 AM EST
Nilanka DharmadasaRank #1,875 · 794 reputationPosted Dec 14, 2009, 6:51 PM EST
If your database is SQL server :
select SUBSTRING(column_name, CHARINDEX('_', column_name) + 1, LEN(column_name) - CHARINDEX('_', column_name)) from table_name
If your database is Oracle :
select substr(column_name,instr(column_name,'_') + 1) from table_name
Replace 'comun_name' with the name of your column and table_name with the name if your table.
If you find my answer useful, please check 'Do you like this answer' check box.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts