Charindex, small functionality but usefull

CHARINDEX (Transact-SQL)

Searches expression2 for expression1 and returns its starting position if found. The search starts at start_location.

Few good scripts with charindex

select CHARINDEX(‘a’, ‘india’)

–result will be 5

select CHARINDEX( ‘,1,’ ,’,1,2,3,’)
– result would be 3
DECLARE @selectedID VARCHAR(10)
SET @selectedID = ‘1,2′
–SET @selectedID = ‘1,5′

Some times we have to pass comma seprated value to sp and have to cross check with table data, its good script here.

it would give you all records which are passed in parameter @selectedID.

DECLARE @t AS TABLE (tID INT)
INSERT INTO @t VALUES (1)
INSERT INTO @t VALUES (2)
INSERT INTO @t VALUES (3)

SELECT * FROM @t
WHERE  CHARINDEX(‘,’ + CONVERT(VARCHAR(5),tID) + ‘,’, ‘,’ + @selectedID + ‘,’) > 0

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*