{"id":5215,"date":"2021-08-15T17:25:32","date_gmt":"2021-08-15T20:25:32","guid":{"rendered":"https:\/\/blog.lucianoreis.com\/?p=5215"},"modified":"2021-09-09T21:45:10","modified_gmt":"2021-09-10T00:45:10","slug":"ms-sql-funcao-para-extrair-somente-numeros-de-uma-string","status":"publish","type":"post","link":"https:\/\/blog.lucianoreis.com\/2021\/08\/15\/ms-sql-funcao-para-extrair-somente-numeros-de-uma-string\/","title":{"rendered":"MS SQL – Extrair Somente N\u00fameros de Uma String"},"content":{"rendered":"\n

Fun\u00e7\u00e3o em linguagem Transact-SQL, a linguagem de programa\u00e7\u00e3o do Microsoft SQL Server, para extrair somente os n\u00fameros de uma string.<\/p>\n\n\n\n

Funcionamento:
+55 (21) 98346-3683 -> 5521983463683
972.347.321-12 -> 97234732112<\/p>\n\n\n\n

CREATE FUNCTION dbo.GetNumeric\n(\n  @strAlphaNumeric VARCHAR(256)\n)\nRETURNS VARCHAR(256)\nAS\nBEGIN\n  DECLARE @intAlpha INT\n  SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)\n  BEGIN\n    WHILE @intAlpha > 0\n    BEGIN\n      SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )\n      SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )\n    END\n  END\n  RETURN ISNULL(@strAlphaNumeric,0)\nEND\nGO<\/pre><\/div>\n\n\n\n

Exemplo de uso:<\/p>\n\n\n\n

UPDATE Cadastro\nSET Indice = dbo.GetNumeric(Telefone)\n\nSELECT dbo.GetNumeric(CPF) AS SomenteNumeros \nFROM Cadastro\nWHERE Cidade = 'Rio de Janeiro'<\/pre><\/div>\n\n\n\n

Se achou \u00fatil, considere assinar este blog preechendo seu e-mail no campo abaixo.<\/p>\n\n\n\t

\n\t\t
\n\t\t\t
\n\t\t\t\t\n\t\t\t\t\t

\n\t\t\t\t\t\t

\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t