T-SQL 2005 String Pattern??

  • How to PRINT below string pattern in T-SQL 2005:

    Input:

    SET @STR = 'HELLO WORLD'

    Output:

    H

    HE

    HEL

    HELL

    HELLO

    HELLO

    HELLO W

    HELLO WO

    HELLO WOR

    HELLO WORL

    HWLLO WORLD

    Thanks in advance.

  • declare @STR varchar(20)

    set @STR = 'HELLO WORLD'

    select SUBSTRING(@str, 1,n)

    from Tally t

    where N<=LEN(@str)

    The 'Tally' table is simple table of numbers.... pls look for articles on Tally table here...

    My Tally Table has only a single column called N.

    How To Post[/url]

  • Try this one:

    Declare @STR varchar(20),@i as int

    Set @STR='HELLOW WORLD'

    Set @i=1

    While @i <= len(@str)

    Begin

    print left(@str,@i)

    Set @i=@i+1

    End

  • Thanks nil...prob solved!!

  • Part of my point here is to turn the OP to the direction of tally tables also.

    I purposely have asked him to look at them.

    Here is a simple way to create a Tally Table (Shamelessly copied from Jeff's article).

    --=============================================================================

    -- Create and populate a Tally table

    --=============================================================================

    --===== Conditionally drop and create the table/Primary Key

    IF OBJECT_ID('dbo.Tally') IS NOT NULL

    DROP TABLE dbo.Tally

    CREATE TABLE dbo.Tally

    (N INT,

    CONSTRAINT PK_Tally_N PRIMARY KEY CLUSTERED (N))

    --===== Create and preset a loop counter

    DECLARE @Counter INT

    SET @Counter = 1

    --===== Populate the table using the loop and couner

    WHILE @Counter <= 11000

    BEGIN

    INSERT INTO dbo.Tally

    (N)

    VALUES (@Counter)

    SET @Counter = @Counter + 1

    END

    http://www.sqlservercentral.com/articles/TSQL/62867/[/url]

    How To Post[/url]

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply