Substring in SQL server

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kewldotnet
    New Member
    • Dec 2006
    • 3

    Substring in SQL server

    Hi Folks...

    I have a string in the format '1.2.3.4.5.6'. I have to write a generic function that will take integer as paramater and will return the string as follows for the above input.
    • ParamaterValue : Output.
    • 1 : 1
    • 2 : 1.2
    • 3 : 1.2.3
    • 4 : 1.2.3.4
  • ck9663
    Recognized Expert Specialist
    • Jun 2007
    • 2878

    #2
    Sounds like an assignment :)

    What do you have so far?

    --- CK

    Comment

    • kewldotnet
      New Member
      • Dec 2006
      • 3

      #3
      Its not an assignment.I have come up with the below solution.

      CREATE FUNCTION [dbo].[StringToTable]
      (
      @inputString nvarchar(max),
      @separator char (1),
      @tokens int
      )
      RETURNS nvarchar(4000)--@ResultTable TABLE ( [String] nvarchar(max) )
      AS
      BEGIN
      DECLARE @ResultTable TABLE ( [String] nvarchar(max) )
      DECLARE @ResultVar nvarchar(4000)
      DECLARE @stringToInsert nvarchar (max)
      DECLARE @cnt int

      WHILE LEN(@inputStrin g) > 0
      BEGIN
      SET @StringToInsert = LEFT(
      @inputString,
      ISNULL(NULLIF(C HARINDEX(@separ ator, @inputString) - 1, -1),
      LEN(@inputStrin g)
      )
      )
      SET @InputString = SUBSTRING(@Inpu tString,

      ISNULL
      (NULLIF
      (CHARINDEX(@sep arator, @InputString),
      0),
      LEN(@InputStrin g)) + 1,
      LEN(@InputStrin g))

      INSERT INTO @ResultTable
      (
      [String]
      )
      VALUES
      (
      @StringToInsert
      )

      END

      SELECT @cnt = count(*) from @ResultTable

      If @cnt>= @tokens
      BEGIN
      SELECT @ResultVar = STUFF((SELECT top (@tokens) '.' + [String] FROM @ResultTable
      FOR XML PATH('')),1, 1, '') ;
      END
      ELSE
      BEGIN
      SELECT @ResultVar = NULL
      END
      RETURN @ResultVar;
      END

      ----------------------
      You can execute the above function as
      select [dbo].[StringToTable]('1.1.2.3','.', 2) will return '1.1'

      I am trying to modify the function without the use of @ResultTable TABLE
      Paramater.

      Comment

      Working...