Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 How can i separate char's and numbers from a word

Author  Topic 

Mng
Yak Posting Veteran

59 Posts

Posted - 2010-03-26 : 07:16:05
Hi, How can i separate characters and numbers from a word using sql query.

For Ex: S1M2I3T4H5 is the word. I am looking for output as


col1 col2
----- -----
SMITH 1234


Please help me to write this query

vaibhavktiwari83
Aged Yak Warrior

843 Posts

Posted - 2010-03-26 : 07:18:58
Look this

[url]http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=141925[/url]

Vaibhav T
Go to Top of Page

Mng
Yak Posting Veteran

59 Posts

Posted - 2010-03-26 : 07:32:49
Vaibhav,

I didn't get that one. Can you please give query directly


quote:
Originally posted by vaibhavktiwari83

Look this

[url]http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=141925[/url]

Vaibhav T

Go to Top of Page

DBA in the making
Aged Yak Warrior

638 Posts

Posted - 2010-03-26 : 07:39:40
Here's a function that will do it.

CREATE FUNCTION dbo.fnStrip(@string AS VARCHAR(100)) RETURNS @SPLIT TABLE
(
String VARCHAR(100),
Number VARCHAR(100)
)
AS
BEGIN
DECLARE @Len INT
DECLARE @Pos INT
DECLARE @OutString VARCHAR(100)
DECLARE @OutNumber VARCHAR(100)
DECLARE @ch CHAR(1)

SELECT @Len = LEN(@string), @Pos = 1, @OutString = '', @OutNumber = ''

WHILE @Pos <= @Len
BEGIN
SET @ch = SUBSTRING(@string, @pos, 1)
IF ISNUMERIC(@ch) != 0
SET @OutNumber = @OutNumber + @ch
ELSE
SET @OutString = @OutString + @ch

SET @Pos = @Pos + 1
END

INSERT INTO @SPLIT VALUES (@OutString, @OutNumber)
RETURN
END
GO

CREATE TABLE #tmp (TestString VARCHAR(100))
GO

INSERT INTO #tmp
SELECT 'AB12CD3EFGH456'
UNION ALL SELECT 'abce123fghi456'
GO

SELECT *
FROM #tmp t
CROSS APPLY dbo.fnStrip(t.TestString)
GO

DROP TABLE #tmp
GO

DROP FUNCTION dbo.fnStrip
GO


There are 10 types of people in the world, those that understand binary, and those that don't.
Go to Top of Page

DBA in the making
Aged Yak Warrior

638 Posts

Posted - 2010-03-26 : 07:41:48
I should point out, the function assumes a maximum input length of 100 characters, and returns a table with 2 varchars. You can adjust to suit your needs.

There are 10 types of people in the world, those that understand binary, and those that don't.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-03-26 : 09:11:23
http://beyondrelational.com/blogs/madhivanan/archive/2007/12/18/extract-only-numbers-from-a-string.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -