-2

I have a query which adds or removes zeros from ID.

SELECT 
    LEFT(STUFF(SystemID +
               REPLICATE('0', 9), 7, 0, REPLICATE('0', 9 - LEN(SystemID))), 9) as OBJECT 
FROM
    Products

So results will be something like this:

ID1230034

How can I remove 'ID' using this query? So it should be:

1230034

Thanks for all help:)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
DJ_TecRoot
  • 93
  • 8

4 Answers4

2

You can use stuff to replace the first 2 chars of the string to an empty string:

SELECT STUFF(LEFT(STUFF(SystemID +
REPLICATE('0',9),7,0,REPLICATE('0',9-LEN(SystemID))),9), 1, 2, '') as OBJECT 
FROM Products
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
1

Use replace function .

SELECT REPLACE(LEFT(STUFF(SystemID +
REPLICATE('0',9),7,0,REPLICATE('0',9-LEN(SystemID))),9),'ID','') as OBJECT from Products
Ronak Patel
  • 630
  • 4
  • 15
0

Use the function Right() -> https://msdn.microsoft.com/en-us/library/ms177532.aspx

assuming your ID's are always the same number of digits, do Right(ID,7)

Alternative Solution:

Use the Substring function -> http://www.w3resource.com/mysql/string-functions/mysql-substring-function.php

This can be helpful if the number of digits change :)

Frenchmassacre
  • 462
  • 4
  • 12
0

A more generic solution that can cope with prefix/suffix non-numeric characters can be found here:

CREATE FUNCTION dbo.udf_GetNumeric
(
     @strAlphaNumeric VARCHAR(256)
)
RETURNS VARCHAR(256)
AS
BEGIN
    DECLARE @intAlpha INT
    SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)

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

    RETURN ISNULL(@strAlphaNumeric,0)
END
GO

Usage:

SELECT dbo.udf_GetNumeric(SystemID) 
from from Products
Community
  • 1
  • 1
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164