从列中选择特定值是由sql查询引起的

时间:2014-07-30 07:00:52

标签: sql-server-2008

我编写了一个查询,它以单列形式返回结果,结果如下所示。

属性名称

MERGE({116288},{116226},{116292},{116249},{116253})

MERGE({116287},{116225},{116291},{116248},{116252})

... ...

我想从此列中仅获取整数值。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这可能不是最好的解决方案。但你可以这样做:

测试数据

DECLARE @tbl TABLE(AttributeNames VARCHAR(100))
INSERT INTO @tbl
    VALUES
    ('MERGE({116288}, {116226}, {116292}, {116249}, {116253})'),
    ('MERGE({116287}, {116225}, {116291}, {116248}, {116252})')

拆分功能

CREATE FUNCTION [dbo].[Split]
(
    @String NVARCHAR(4000),
    @Delimiter NCHAR(1)
)
RETURNS TABLE 
AS
RETURN 
(
    WITH Split(stpos,endpos) 
    AS(
        SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
        UNION ALL
        SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
            FROM Split
            WHERE endpos > 0
    )
    SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
        'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),
         LEN(@String)+1)-stpos)
    FROM Split
)
GO

然后查询如下:

SELECT
    CAST(tbl2.Data AS INT)
FROM
    @tbl AS tbl
    CROSS APPLY
    (
        SELECT
            LTRIM(REPLACE(REPLACE(REPLACE(REPLACE(split.Data,'{',''),'}',''),
            'MERGE(',''),')','')
            )as Data
        FROM
            dbo.Split(tbl.AttributeNames,',') as split
    ) AS tbl2