Home Forums SQL Server 2014 Administration - SQL Server 2014 Two sets of numbers, one 6 in LEN, the other 7..need to match the first 6 digits in both as a query? RE: Two sets of numbers, one 6 in LEN, the other 7..need to match the first 6 digits in both as a query?

  • Luis Cazares - Monday, March 27, 2017 9:57 AM

    Here are my suggestions depending on the data type.
    DECLARE @NUMLIST TABLE
    (
    NM_ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED
    ,SKU BIGINT  NOT NULL
    );
    INSERT INTO @NUMLIST(SKU)
    VALUES (7856614),(7956615),(7956616),(7756616),(795661);

    DECLARE @NUMDIG INT = 6;

    SELECT long.NM_ID,
      long.SKU,
      ISNULL(short.SKU, long.SKU) AS matching
    FROM @NUMLIST long
    LEFT
    JOIN @NUMLIST short ON (long.SKU / 10 = short.SKU AND LEN( long.sku) = @NUMDIG + 1)
    GO

    DECLARE @NUMLIST TABLE
    (
    NM_ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED
    ,SKU varchar(15)  NOT NULL
    );
    INSERT INTO @NUMLIST(SKU)
    VALUES (7856614),(7956615),(7956616),(7756616),(795661);

    DECLARE @NUMDIG INT = 6;

    SELECT long.NM_ID,
      long.SKU,
      ISNULL(short.SKU, long.SKU) AS matching
    FROM @NUMLIST long
    LEFT
    JOIN @NUMLIST short ON (long.SKU LIKE short.SKU + '_' AND LEN( long.sku) = @NUMDIG + 1)

    I will only be comparing nvarchar(20) which is mainly INT data, I only care about INT's up to 12 in LEN