views:

824

answers:

5

I need query (to be more specific, it is view, not query) that will return string column. String will be code, that might be prefixed with two letters (LJ). If it is prefixed -- prefix have to be trimmed. If there is no prefix present, it should be left untouched. Is it possible to do such thing in SQL? Server is FirebirdSQL 1.5.


None of given solutions worked, but with their help, I was able to figure it out by myself. Substring function does exist, but has different syntax. Instead of commas you have to use proper keywords:

Substring(col from pos for count)
+1  A: 
SELECT
  CASE Substring(columnName, 2, 2) IS 'LJ' THEN Subsrtring(columnName, 2, LEN(columnName) -2) ELSE columnName END

That's what I think you are looking for, haven't executed to test but you get the gist...

Hope it helps!

Mark Kadlec
you want the first two characters, so isn't _Substring(columnName, 2, 2)_ wrong?
KM
Oops, good catch, should be SUBSTRING(columnName, 1, 2).
Mark Kadlec
+2  A: 

yes, instead of selecting the column itself, write an expression that replaces the prefix LJ with nothing

   Select case When colName Like 'LJ%' 
                Then SubString([colName], 2, Len(colName) - 2)
                Else ColName End
   From ...
Charles Bretana
I agree with this. But one thing I would add is that this type of action screams to me to be put into a seperate SQL function so that it can be used elsewhere if needed. For instance, pass in the string to be trimmed, a prefix code and the number of characters to trim so that it becomes more flexible. Just a thought....
Yoav
@Yoav, to me this screams put separate info into separate columns and you won't need to do hacks like this! alter the table to have two columns!!!!
KM
@KM, you are surely right, but as it often happens - it doesn't depend on me. I have some database design, and have to fit to it.
samuil
This solution works, but sadly not in FirebirdSQL. However, when I learned what is name of needed `SQL` function I was able to find fb specific solution.
samuil
A: 
select case 
           when substring(MyColumn, 1, 2) = 'LJ' 
               then substring(MyColumn, 3, len(MyColumn) - 2) 
           else 
               MyColumn 
       end
RedFilter
A: 

You could do it with string manipulation:

SELECT CONCAT(REPLACE(LEFT(column_name,2), 'LJ', ''), SUBSTRING(column_name, 3))

Not sure this would work in Firebird (tested on Mysql).

Brian Fisher
Firebird doesn't appear to have a REPLACE function, otherwise it'd have been my answer too.
OMG Ponies
@ rexem Firebird have REPLACE in 2.1 http://www.firebirdsql.org/refdocs/langrefupd21-intfunc-replace.html
Hugues Van Landeghem
A: 

Get a copy of FreeUDFLib, it have a LOT of functions for strings, math, date, convertions, blob handling, etc. It will do what you want, an a lot more of things

José Romero