Question : SQL Query Code

I have to tables. Table 1 is as follows


Called Account:
98798798797
13123123123
13123123123
12423123127

Table 2 is as follows:

Code           GroupName
12                  Group A
98                  Group B
1                    Group A
131                Group 5
124                Group 4

What i want to do is select a code from table 2 eg, code 12 and then update all records in table A with numbers starting with 12 to group A. The same for all other codes. Please help.

Answer : SQL Query Code

Interesting question... problem lies with figuring out how to match the most specific code to the number. My mechanism uses the length of the Area Code prefix to help figure out the most appropriate one. Note that I have just taken your supplied data and quickly made some CTEs out of it. Just to show you how the SELECT would work...

WITH CalledNumbers AS (
      SELECT '98798798797' AS Account
      UNION SELECT '19123123123' --I have changed this value from your original post
      UNION SELECT '13123123123'
      UNION SELECT '12423123127'      
), AreaCodes AS (
      SELECT '12' AS Prefix, 'Group A' AS GroupName
      UNION SELECT '98', 'Group B'
      UNION SELECT '1', 'Group A'
      UNION SELECT '131', 'Group 5'
      UNION SELECT '124', 'Group 4'
)
SELECT CalledNumbers.*, AreaCodes.*
FROM CalledNumbers
      LEFT OUTER JOIN AreaCodes ON CalledNumbers.Account LIKE AreaCodes.Prefix + '%'
WHERE LEN(AreaCodes.Prefix) = (SELECT MAX(LEN(Prefix)) FROM AreaCodes WHERE CalledNumbers.Account LIKE AreaCodes.Prefix + '%')

And in order to do your update as required:

UPDATE CalledNumbers SET CalledNumbers.GroupName = AreaCodes.GroupName FROM
CalledNumbers
      LEFT OUTER JOIN AreaCodes ON CalledNumbers.Account LIKE AreaCodes.Prefix + '%'
WHERE LEN(AreaCodes.Prefix) = (SELECT MAX(LEN(Prefix)) FROM AreaCodes WHERE CalledNumbers.Account LIKE AreaCodes.Prefix + '%')
Random Solutions  
 
programming4us programming4us