Click here to Skip to main content
16,004,828 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a single column table with values as below:

ACT ONLY
NSW ONLY
QLD ONLY

If i now pass a string say, "ABC - QLD ONLY", then i need to get back "ABC" as a result (as "QLD ONLY" is in the table row).
Can anyone please help me solve this?

Thank you.

What I have tried:

I have tried creating a function, with no success.
Posted
Updated 8-Jan-18 12:43pm

SQL
try

<pre>

declare @table table ( col nvarchar(50) )

insert into @table values ('ACT ONLY')
insert into @table values ('NSW ONLY')
insert into @table values ('QLD ONLY')

declare @find  nvarchar(50)
declare @result  nvarchar(50)
set @find ='ABC - QLD ONLY'
set  @result =    ( select top 1 col from @table where @find like '%'+col+'%')
if(@result is not null )
begin
 select @result = REPLACE(@find , @result ,'') 
  select @result = REPLACE(@result , '-' ,'') 
end
select  @result -- ABC
 
Share this answer
 
Comments
Maciej Los 9-Jan-18 3:36am    
5ed!
Karthik_Mahalingam 9-Jan-18 4:18am    
Thank you Maciej
This should work too
SQL
DECLARE @temp TABLE (Col1 VARCHAR(50))
DECLARE @input VARCHAR(50)

SET @input = 'ABC - QLD ONLY'

INSERT INTO @temp
	SELECT 'ACT ONLY' UNION SELECT 'NSW ONLY' UNION SELECT 'QLD ONLY'

SELECT REPLACE(REPLACE(@input, col1, ''),' - ','') FROM @temp
WHERE CHARINDEX(col1,@input)  > 0
 
Share this answer
 
Comments
Maciej Los 9-Jan-18 3:37am    
5ed!
Bryian Tan 9-Jan-18 9:00am    
Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900