Search code examples
sqlsql-servert-sqlsql-server-express

How to check id in a string column in a SQL Server 2008 table


I have a table that stores integer IDs of other table as comma separated string column. Now I want to find all rows in this table that have a specific ID in this string column.

Example

InwardHeader 
(
     inhdrid numeric(18, 0), 
     inwardno numeric(10, 0), 
     inwarddt datetime, 
     item numeric(10), 
     qty numeric(18, 2)
)

StockOutward 
(
    Stkouthdrid numeric(18, 0), 
    stkoutno numeric(18, 0), 
    stkoutdt datetime, 
    item numeric(10), 
    inwardids varchar(100)
)

The column StockOutward.inwardids contains comma separated values of multiple InwardHeader.inhdrid

I want to find rows from stockoutward which contain inwardheader.inhdrid for a specific value


Solution

  • First of all is not good practice to store id on string field delimited by comma, You should use 1:N relationships, Anyway i prepared a solution for you(tested) like below:

    SELECT [Stkouthdrid]
          ,[stkoutno]
          ,[stkoutdt]
          ,[item]
          ,[inwardids]
      FROM [test].[dbo].[StockOutward] 
      where  CHARINDEX((
      SELECT convert(varchar(10),[inhdrid])
      FROM [test].[dbo].[InwardHeader]
      where [inhdrid]=0), [inwardids]) > 0
    

    Hope it Helps :) enter image description here