Skip to content
Advertisement

How to search for separated values in cloumns from a merged values column

I have a database where the data I need to work with is stored into two different columns. I also need to import an excel file and the data in this excel file is all together only separated by a dash. So either I need to figure out how to create a query, maybe an alias, or how to split the column by the dash and then make the query with the data split up.

The code I was trying was the following:

SELECT 
    CAST (dbo_predios.codigo_manzana_predio as nvarchar(55))+'- 
    '+CAST(dbo_predios.codigo_lote_predio as nvarchar(55)) as ROL_AVALUO 
FROM dbo_predios 
WHERE ROL_AVALUO like '%9132-2%'

That is one way I tried, but I don’t know well how to split by a determined symbol. The data on the excel comes in the exact same way that I wrote in the “like” portion of the code.

Advertisement

Answer

I believe this is what you are after from the sounds of it:

SELECT
 [locateDashInString] = CHARINDEX('-', e.FieldHere, 0) --just showing you where it finds the dash
,[SubstringBeforeItemLocated] = 
    SUBSTRING(
                e.FieldHere --string to search from
                ,0 --starting index
                ,CHARINDEX('-', e.FieldHere, 0) --index of found item
              )
,[SubstringAfterItemLocated] = 
    SUBSTRING(
                e.FieldHere --string to search from
                ,CHARINDEX('-', e.FieldHere, 0) + 1 --starting index for substring
                ,LEN(e.FieldHere) --finish substring at this point
             )
FROM ExcelImportedDataTable e

The locateDashInString column is just to show you where it finds the ‘-‘ symbol, you don’t actually need it, the other two columns are a split of the value so ‘9132-2’ split into two values/two columns.

**Just note that this will only work if you always have the format of val1-val2 in the data. Aslong as the format is the same it should be fine.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement