Today, we will explain about SQL Split Function to Split an Input String. Generally when posting an article in a blog, we have to define tags (Like  C#.NET, AJAX, ASP.NET,HTML) upon the article. We usually take these tags in a TextBox with separated them by comma(,). To insert these into database we have two ways to do.

First Method using C# :

Using C# you can split the TextBox items and use a for loop to insert into the database. Code is as follow.
   
string []tags = txtTags.Text.<span class="IL_AD" id="IL_AD10">Trim</span>().Split(',');
 
/* With for loop */
for (int i=0;i<tags.Count ;i++)
{
 /* perform db query with tags[i].ToSting();
}
 
/* with foreach */
foreach (string i in tags)
{
  /* perform db query with i.ToSting();
}

Second SQL Method :

Here in the SQL we pass the whole items of TextBox into SQL function to split it and then insert these into specific table. Lets see how to do this.
   
CREATE FUNCTION SplitText
(   
      @Input NVARCHAR(MAX),
      @Character CHAR(1)
)
RETURNS @Output TABLE (
      Item NVARCHAR(1000)
)
AS
BEGIN
      DECLARE @StartIndex INT, @EndIndex INT
 
      SET @StartIndex = 1
      IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
      BEGIN
            SET @Input = @Input + @Character
      END
 
      WHILE CHARINDEX(@Character, @Input) > 0
      BEGIN
            SET @EndIndex = CHARINDEX(@Character, @Input)
           
            INSERT INTO @Output(Item)
            <span class="IL_AD" id="IL_AD12">SELECT</span> SUBSTRING(@Input, @StartIndex, @EndIndex - 1)
           
            SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
      END
 
      RETURN
END
GO
 
-- Create a temporary table to insert tags
create #tblTemp
(
Id identity (1,1),
tag nvarchar(50)
)
 
-- Inserting into tmpTable
insert into #tblTemp (temp) values
SELECT Item FROM dbo.SplitText('ASP.NET,C#.NET,ADO.NET,JavaScript', ',') 
-- Seperated by Comma(,). Place any thing according to you.


Execute your SQL batch query to inserting the tags into table.

Best ASP.NET 4.6 Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.