how to compare two string variables

  • Hi,

    I need to find out if the first string is in second string. How can I compare two string variables as following:

    declare @s1 as varchar

    declare @s2 as varchar

    set @s1 = '1232'

    set @s2 = 'tete,1232'

    select patindex('%1232%','tete,1232') will return a number

    Can I do something like select patindex (@s1, @s2)?

  • Yes you can... like this...

    DECLARE @S1 VARCHAR(100)

    DECLARE @S2 VARCHAR(100)

    SET @S1 = '5'

    SET @S2 = '1,2,3,4,55,6'

    SELECT PATINDEX('%'+@S1+'%',@S2)

    But, you notice that in this case, the answer is incorrect. There is no "5" in @S2... the number is incorrectly being returned because of the "55" the "5" picks up on.

    If you're not going to split the data, then you must wrap the delimiters in the search on both @S1 and @S2... like this...

    DECLARE @S1 VARCHAR(100)

    DECLARE @S2 VARCHAR(100)

    SET @S1 = '5'

    SET @S2 = '1,2,3,4,55,6'

    SELECT PATINDEX('%,'+@S1+',%' , ','+@S2+',')

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

  • try this one also ....

    DECLARE @s1 varchar(16)

    DECLARE @s2 varchar(16)

    SET @s1 = '1232'

    SET @s2 = 'tete,1232'

    SELECT @s1,@s2

    SELECT SUBSTRING(@s2,CHARINDEX(@s1,@s2,1),LEN(@s1))

    ---

  • Thanks !

  • sqluser (2/20/2008)


    try this one also ....

    DECLARE @s1 varchar(16)

    DECLARE @s2 varchar(16)

    SET @s1 = '1232'

    SET @s2 = 'tete,1232'

    SELECT @s1,@s2

    SELECT SUBSTRING(@s2,CHARINDEX(@s1,@s2,1),LEN(@s1))

    ---

    Careful!!!! You must still include the delimiter wrapping or you will get false returns.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)

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

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