简体   繁体   中英

split column value of sql server in C#

There is a column "AppendedData" in "Route" table . It stores data in this format

-------------
ID |  AppendedData
1  |  abc : xyz
2  |  123a : gvk
--------------

What I want is to write a search query over this "AppendedData" in where clause by spliting/substring it in two parts . The part before ":" is to be used in matching the values.

The current application that i am working is an old one so I can't go for writing an stored procedure . So what I am left is writing query in c# and executing it and returning a datable. So how can I do this in c#??

I was trying this in sql server till now it is returning the second part ie, after ":".

my query:

select SUBSTRING(AppendedData,CHARINDEX(':',AppendedData)+1, 100) from  route

Try this,

In SQL

declare @route  TABLE
(  
    [ID] [int] NOT NULL,  
    [AppendedData] varchar (50) NOT NULL  
)   

insert into @route values (1, 'abc : xyz') 
insert into @route values (2, '123a : gvk') 

select SUBSTRING(AppendedData,CHARINDEX(':',AppendedData)+1, 100) from @route where             SUBSTRING(AppendedData,1, CHARINDEX(':', AppendedData)-1) = '123a'  

In C#

var lstRoutes = new List<Route>
{
    new Route {ID = 1, AppendedData = "abc : xyz"},
    new Route {ID = 2, AppendedData = "123a : gvk"},
                                   };
var result = lstRoutes.Where(r1 => r1.AppendedData.Split(':')[0].Trim() == "abc")
            .Select(r => new { r.ID, right = r.AppendedData.Split(':')[1] });

If you want to match the first part of the value, you can try something like this

SELECT * FROM Route WHERE AppendData LIKE '123a :%'

and it would match your row with ID 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM