HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to port LTRIM from Oracle to SQL Server?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
fromltrimhowsqlportserveroracle

Problem

Moving an application from Oracle to SQL Server, I have this pseudo Oracle PL/SQL:

SELECT LTRIM(MyColumn, '-, ') FROM MyTable


I.e. I'm using Oracle's LTRIM with a second argument, specifying the characters to trim from the left side of the string.

Unfortunately, the T-SQL version of LTRIM doesn't allow me to specify the characters to trim.

Currently, I'm rather clueless how to migrate that LTRIM. I'm even thinking about processing the results in my hosting C# application, after I read the MyColumn.

This looks rather inelegant to me.

My question:

Is there any meaningful way of getting an LTRIM-like functionality for T-SQL to pass the characters to trim away?

Edit 1:

I need to replace -, , and ` from the beginning of the string.

E.g.:

-----, ,,, This is ,- a test,---,


would result in

This is ,- a test,---,


Edit 2:

I strongly hope this isn't an XY problem.

Maybe rewriting my whole query would remove the need for
LTRIM altogether, although I would rather focus on porting it as 1:1 as possible and later question the usefulness of the LTRIM`.

Solution

Yeehaw.

DECLARE @MyTable TABLE ( MyColumn VARCHAR(100) );

INSERT @MyTable ( MyColumn )
    VALUES ( '-----, ,,, This is ,- a test,---,' );

SELECT *, 
        SUBSTRING(mt.MyColumn, ca.p, LEN(mt.MyColumn))
FROM @MyTable AS mt
CROSS APPLY ( SELECT * 
              FROM (VALUES (PATINDEX ('%[^ ,-]%', MyColumn))
            ) AS x (p) ) AS ca;

Code Snippets

DECLARE @MyTable TABLE ( MyColumn VARCHAR(100) );

INSERT @MyTable ( MyColumn )
    VALUES ( '-----, ,,, This is ,- a test,---,' );

SELECT *, 
        SUBSTRING(mt.MyColumn, ca.p, LEN(mt.MyColumn))
FROM @MyTable AS mt
CROSS APPLY ( SELECT * 
              FROM (VALUES (PATINDEX ('%[^ ,-]%', MyColumn))
            ) AS x (p) ) AS ca;

Context

StackExchange Database Administrators Q#162227, answer score: 6

Revisions (0)

No revisions yet.