如何使用标量函数获取值?

时间:2013-12-02 18:48:11

标签: sql sql-server sql-server-2008 tsql

我在数据库表中有一个包含

等数据的列

(102-sled,105-fed,106-gov,107,edu)

我想要一个像

这样的结果
(102,105,106,107) just i want to skip some values 

2 个答案:

答案 0 :(得分:2)

CREATE FUNCTION GetNumbers
 (@string varchar(1000))
 RETURNS VARCHAR(1000)
 AS
 BEGIN


    WHILE PATINDEX('%[^0-9]%',@string) <> 0
     BEGIN
      SET @string = STUFF(@string,PATINDEX('%[^0-9]%',@string),1,'')
     END

   RETURN   @string;
 END

DECLARE @string VARCHAR(1000)
SET @string = 'sk123;fja4567afj;as890'


SELECT dbo.GetNumbers(@string)

<强>结果

1234567890

修改

尝试这样的事情

CREATE TABLE #temp (ID INT, Value VARCHAR(20))
INSERT INTO #temp
VALUES
(1,'102-sled'),(1,'105-fed'),(1,'106-gov'),(1,'107'),(1,'edu')

SELECT DISTINCT ID , STUFF(Q.List, 1, 2, '') NumberList
FROM #temp t CROSS APPLY(
                    SELECT ', '+ dbo.GetNumbers(Value) [text()]
                    FROM #temp 
                    WHERE #temp.ID = t.ID
                    FOR XML PATH('')
                    ) Q(List)

<强>结果

ID  NumberList
1   102, 105, 106, 107, 

答案 1 :(得分:0)

CREATE FUNCTION NUM (@T VARCHAR(20))
RETURNS VARCHAR(20)
AS
BEGIN
DECLARE @I TINYINT=1
DECLARE @R VARCHAR(20)=NULL
WHILE @I<=LEN(@T)
BEGIN
IF (ASCII(SUBSTRING(@T,@I,1))>=48 AND ASCII(SUBSTRING(@T,@I,1))<=57)
BEGIN
SET @R=CONCAT(@R,SUBSTRING(@T,@I,1))
END
SET @I+=1
END
RETURN @R
END

例如:

CREATE TABLE #T
(I VARCHAR(20))
INSERT INTO #T
SELECT '105-fed'
UNION ALL
SELECT '102-sled'
UNION ALL
SELECT '106-gov'
UNION ALL
SELECT '107'
UNION ALL
SELECT 'EDU'
SELECT dbo.NUM(I)
FROM #T
WHERE dbo.NUM(I) IS NOT NULL
DROP TABLE #T

结果:

(4行(s)受影响)


105 102 106 107 (4行受影响)