2013-10-05 47 views
0

我有一個名爲'name'的類型字符,如何打印至少有一位數字/至少三位數字/正好五位數字的值?例如:如何在T-sql中顯示數字的值?

Name 
----------- 
'name1' 
'name2356' 
'name12567' 
  1. 至少一位會返回'name1', 'name2356' and 'name12567'
  2. 至少有三位數字將返回'name2356' and 'name12567'
  3. 正是五位將返回'name12567'
+1

你能舉一些例子嗎? –

+0

你的意思是當列中包含字符串中給定數量的數字?以下http://technet.microsoft.com/en-us/library/ms181984.aspx將幫助您 –

+1

請不要只是要求我們爲您解決問題。告訴我們你是如何試圖自己解決問題的,然後向我們展示結果是什麼,並告訴我們爲什麼你覺得它不起作用。請參閱「[您嘗試過什麼?](http://whathaveyoutried.com/)」,以獲得一篇您最近需要閱讀的優秀文章。 –

回答

1
CREATE FUNCTION dbo.[udf_CountNumericCharacters](@strText VARCHAR(1000)) 
RETURNS VARCHAR(1000) 
AS 
BEGIN 
    WHILE PATINDEX('%[^0-9]%', @strText) > 0 
    BEGIN 
     SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '') 
    END 
    RETURN LEN(@strText) 
END 

-- Greater than one 
SELECT * 
FROM Test 
WHERE dbo.[udf_CountNumericCharacters]([Name]) > 1 

-- Greater than three 
SELECT * 
FROM Test 
WHERE dbo.[udf_CountNumericCharacters]([Name]) > 3 

-- Exactly 5 
SELECT * 
FROM Test 
WHERE dbo.[udf_CountNumericCharacters]([Name]) = 5 

快速搜索將讓你一百萬個不同的方式來打印這些結果。

0

你可以使用UDF

create function dbo.HasDigits(@Text VarChar(80), @Digits int) 
returns bit 
as 
begin 
    declare @i int = datalength(@text) 
    while @i>=1 and @digits>0 begin 
    if ISNUMERIC(substring(@text,@i,1))=1 
    set @[email protected] 
    else 
    set @i = 1 
    set @[email protected] - 1 
    end 

    return case when @digits>0 then 0 else 1 end 
end 

要使用它,執行

select * from MyTable where dbo.HasDigits(Name,3) = 1 
相關問題