Is there any LTRIM function for MS ACCESS 2007? - sql

i am trying to ltrim 3 or 4 zeros from a column in Access 2007 but not getting any result where the data-type is text(from a csv data).

From what I read, MS Access in fact should support LTRIM. Here is a workaround in case you need it:
SELECT
IIF(string LIKE "0000*",
MID(string, 5),
IIF(string LIKE "000*", MID(string, 4), string)) output
FROM yourTable;

Here are a couple of quickly written LTrim & RTrim functions to operate with characters other than spaces:
Function LTrimChr(strStr As String, strChr As String) As String
If strStr Like strChr & "*" Then
LTrimChr = LTrimChr(Mid(strStr, 2), strChr)
Else
LTrimChr = strStr
End If
End Function
Function RTrimChr(strStr As String, strChr As String) As String
If strStr Like "*" & strChr Then
RTrimChr = RTrimChr(Left(strStr, Len(strStr) - 1), strChr)
Else
RTrimChr = strStr
End If
End Function
Expects the strChr to be a single character, e.g.:
?LTrimChr("000123456789000","0")
123456789000
?RTrimChr("000123456789000","0")
000123456789

In case of digits only, you can use Val to strip leading zeroes:
LTrimmedValue = CStr(Val(Value))
' "000123456789000" -> "123456789000"

MS Access supports ltrim(), but only for spaces. So, assuming that your string has no spaces, you can use replace() and ltrim():
select replace(ltrim(replace(col, '0', ' ')), ' ', '0')
If you do have spaces, there is often a character you don't have, so you can replace the spaces first:
select replace(replace(ltrim(replace(replace(col, ' ', '~'
), '0', ' '
)
), ' ', '0'
), '~', ' '
)

Related

GROUP_CONCAT() error in h2 [42001-214] , [42122-214]

i keep getting this error GROUP_CONCAT(""""[*],a.montant, a.type_avance,a.date_avance,
a.remark SEPARATOR '') as Avance [42001-214] ,and after
i removed GROUP_CONCAT to test the code i got the error:
Column "" not found; SQL statement [42122-214]
here is my code:
SELECT i.n_dossier , concat(\"<html>\",i.nom_prenom,\"<br></html>\")
,concat(\"<html>\",i.vehicule,\"<br></html>\"),i.prime_totale ,"
+ " i.date_effet , i.date_echean ,GROUP_CONCAT(\"<html>\",a.montant,"
+ " a.type_avance,a.date_avance,a.remark SEPARATOR \"<br>\") as Avance ,i.reste ,i.GSM,"
+ "i.observation ,\"</html>\" FROM info_impayee i LEFT JOIN avance a ON i.n_dossier = "
+ " a.n_dossier GROUP by i.n_dossier,i.date_dossier,i.anuller having i.anuller = ' active '
You must repalce
GROUP_CONCAT("<html>",a.montant, a.type_avance,a.date_avance,a.remark SEPARATOR "<br>")
with
GROUP_CONCAT(CONCAT("<html>",a.montant, a.type_avance,a.date_avance,a.remark) SEPARATOR "<br>")
GROUP_CONCAT needs to have 1 column, as you see in the samle CONCAT will do that.
I don't why you use single quorted ' active 'and doou

How to generate column with row number?

I'm trying to make an query that will generate column with unique row number generated incrementally. My table with data don't have any unique value.
I was trying to get Gustav script, but I only manage to get it return 1 in every row.
Public Function RowCounter( _
ByVal strKey As String, _
ByVal booReset As Boolean, _
Optional ByVal strGroupKey As String) _
As Long
' Builds consecutive RowIDs in select, append or create query
' with the possibility of automatic reset.
' Optionally a grouping key can be passed to reset the row count
' for every group key.
'
' Usage (typical select query):
' SELECT RowCounter(CStr([ID]),False) AS RowID, *
' FROM tblSomeTable
' WHERE (RowCounter(CStr([ID]),False) <> RowCounter("",True));
'
' Usage (with group key):
' SELECT RowCounter(CStr([ID]),False,CStr[GroupID])) AS RowID, *
' FROM tblSomeTable
' WHERE (RowCounter(CStr([ID]),False) <> RowCounter("",True));
'
' The Where statement resets the counter when the query is run
' and is needed for browsing a select query.
'
' Usage (typical append query, manual reset):
' 1. Reset counter manually:
' Call RowCounter(vbNullString, False)
' 2. Run query:
' INSERT INTO tblTemp ( RowID )
' SELECT RowCounter(CStr([ID]),False) AS RowID, *
' FROM tblSomeTable;
'
' Usage (typical append query, automatic reset):
' INSERT INTO tblTemp ( RowID )
' SELECT RowCounter(CStr([ID]),False) AS RowID, *
' FROM tblSomeTable
' WHERE (RowCounter("",True)=0);
'
' 2002-04-13. Cactus Data ApS. CPH
' 2002-09-09. Str() sometimes fails. Replaced with CStr().
' 2005-10-21. Str(col.Count + 1) reduced to col.Count + 1.
' 2008-02-27. Optional group parameter added.
' 2010-08-04. Corrected that group key missed first row in group.
Static col As New Collection
Static strGroup As String
On Error GoTo Err_RowCounter
If booReset = True Then
Set col = Nothing
ElseIf strGroup <> strGroupKey Then
Set col = Nothing
strGroup = strGroupKey
col.Add 1, strKey
Else
col.Add col.Count + 1, strKey
End If
RowCounter = col(strKey)
Exit_RowCounter:
Exit Function
Err_RowCounter:
Select Case Err
Case 457
' Key is present.
Resume Next
Case Else
' Some other error.
Resume Exit_RowCounter
End Select
End Function
Sql query that I'm trying to get working is like this:
SELECT RowCounter("Query1",False) AS RowID, *
FROM Query1
WHERE (RowCounter("Query1",False)<>RowCounter("",True));
What am I missing to get this to work?
You are passing a fixed string as the parameter - and this gets No. 1.
Use the ID of the records of the query, like:
SELECT RowCounter(CStr([ID]),False) AS RowID, *

How do I convert an empty string into a numerical null in Access SQL_

I want to populate a table with data from a staging table. The interesting column in the staging table has the datatype text but is otherwise filled with either values that are parsable as doubles or are the empty string (ie "4.209", "42" or ""). The according column in the destination table has the data type double.
The SQL Statement I am executing is
insert into dest (.., theColumn, ... ) select ...., theColumn, .. from src
When I execute the statement (using ADO) I receive a Data type mismatch in criteria expression error).
If I replace theColumn with null, it works without error. So, I figure I should somehow convert empty strings to nulls. Is this possible?
Use an IIf() expression: if theColumn contains a string which represents a valid number, return that number; otherwise return Null.
SELECT IIf(IsNumeric(theColumn), Val(theColumn), Null) FROM src
My first impulse was to use IsNumeric(). However I realized this is a more direct translation of what you requested ...
SELECT IIf(theColumn='', Null, Val(theColumn)) FROM src
Convert empty strings to zero maybe also work.
insert into dest (.., theColumn, ... ) select ...., theColumn+0, .. from src
You can use Val to convert "" to 0:
insert into dest (.., theColumn, ... ) select ...., Val(theColumn), .. from src
To insert Null, use a function like this:
' Converts a value of any type to its string representation.
' The function can be concatenated into an SQL expression as is
' without any delimiters or leading/trailing white-space.
'
' Examples:
' SQL = "Select * From TableTest Where [Amount]>" & CSql(12.5) & "And [DueDate]<" & CSql(Date) & ""
' SQL -> Select * From TableTest Where [Amount]> 12.5 And [DueDate]< #2016/01/30 00:00:00#
'
' SQL = "Insert Into TableTest ( [Street] ) Values (" & CSql(" ") & ")"
' SQL -> Insert Into TableTest ( [Street] ) Values ( Null )
'
' Trims text variables for leading/trailing Space and secures single quotes.
' Replaces zero length strings with Null.
' Formats date/time variables as safe string expressions.
' Uses Str to format decimal values to string expressions.
' Returns Null for values that cannot be expressed with a string expression.
'
' 2016-01-30. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function CSql( _
ByVal Value As Variant) _
As String
Const vbLongLong As Integer = 20
Const SqlNull As String = " Null"
Dim Sql As String
Dim LongLong As Integer
#If Win32 Then
LongLong = vbLongLong
#End If
#If Win64 Then
LongLong = VBA.vbLongLong
#End If
Select Case VarType(Value)
Case vbEmpty ' 0 Empty (uninitialized).
Sql = SqlNull
Case vbNull ' 1 Null (no valid data).
Sql = SqlNull
Case vbInteger ' 2 Integer.
Sql = Str(Value)
Case vbLong ' 3 Long integer.
Sql = Str(Value)
Case vbSingle ' 4 Single-precision floating-point number.
Sql = Str(Value)
Case vbDouble ' 5 Double-precision floating-point number.
Sql = Str(Value)
Case vbCurrency ' 6 Currency.
Sql = Str(Value)
Case vbDate ' 7 Date.
Sql = Format(Value, " \#yyyy\/mm\/dd hh\:nn\:ss\#")
Case vbString ' 8 String.
Sql = Replace(Trim(Value), "'", "''")
If Sql = "" Then
Sql = SqlNull
Else
Sql = " '" & Sql & "'"
End If
Case vbObject ' 9 Object.
Sql = SqlNull
Case vbError ' 10 Error.
Sql = SqlNull
Case vbBoolean ' 11 Boolean.
Sql = Str(Abs(Value))
Case vbVariant ' 12 Variant (used only with arrays of variants).
Sql = SqlNull
Case vbDataObject ' 13 A data access object.
Sql = SqlNull
Case vbDecimal ' 14 Decimal.
Sql = Str(Value)
Case vbByte ' 17 Byte.
Sql = Str(Value)
Case LongLong ' 20 LongLong integer (Valid on 64-bit platforms only).
Sql = Str(Value)
Case vbUserDefinedType ' 36 Variants that contain user-defined types.
Sql = SqlNull
Case vbArray ' 8192 Array.
Sql = SqlNull
Case Else ' Should not happen.
Sql = SqlNull
End Select
CSql = Sql & " "
End Function

Nested Cell to string

I have the following problem:
Objective (high-level):
I would like to convert ESRI Shapefiles into SQL spatial data. For that purpose, I need to adapt the synthax.
Current status / problem:
I constructed a the following cell array:
'MULTIPOLYGON(' {1x2332 cell} ',' {1x916 cell} ',' {1x391 cell} ',' {1x265 cell} ')'
with in total 9 fields. This cell array contains the following 'nested' cell arrays: {1x2332 cell}, {1x916 cell}, {1x391 cell}, {1x265 cell}. As an example, 'nested' cell {1x2332 cell} has the following form:
'((' [12.714606000000000] [42.155628000000000] ',' [12.702529999999999] [42.152873999999997] ',' ... ',' [12.714606000000000] [42.155628000000000] '))'
However, I would like to have the entire cell array (including all 'nested cells') as one string without any spaces (except the space between the numbers (coordinates)). Would you have an idea how I could get to a solution?
Thank you in advance.
You probably need loops for this.
Consider a smaller example:
innerCell1 = {'((' [12.714606000000000] [42.155628000000000] ',' [12.702529999999999] [42.152873999999997] ',' [12.714606000000000] [42.155628000000000] '))'};
outerCell = {'MULTIPOLYGON(' innerCell1 ',' innerCell1 ')'};
You can go along these lines:
outer = outerCell; %// will be overwritten
ind_outer = find(cellfun(#iscell, outer)); %// positions of inner cell arrays in `outer`
for m = ind_outer
inner = outer{m};
ind_inner = cellfun(#isnumeric, inner); %// positions of numbers in `inner`
ind_inner_space = find(ind_inner(1:end-1) & ind_inner(2:end)); %// need space
ind_inner_nospace = setdiff(find(ind_inner), ind_inner_space); %// don't need
for n = ind_inner_space
inner{n} = [num2str(inner{n}) ' ']; %// convert to string with space
end
for n = ind_inner_nospace
inner{n} = num2str(inner{n}); %// convert to string, without space
end
outer{m} = [inner{:}]; %// concatenate all parts of `inner`
end
str = [outer{:}]; %// concatenate all parts of `outer`
This results in the string
str =
MULTIPOLYGON(((12.7146 42.1556,12.7025 42.1529,12.7146 42.1556)),((12.7146 42.1556,12.7025 42.1529,12.7146 42.1556)))

Regex: match SQL PRINT blocks with quoted text in it

I have the following text I am trying match using regular expressions:
PRINT CONVERT(NVARCHAR,
CURRENT_TIMESTAMP, 111) + ' ' +
CONVERT(NVARCHAR, CURRENT_TIMESTAMP,
108)
+ ' -Test Mode : ' + (CASE WHEN #turbo_mode_ind = 1 THEN
'some text ''test'' some more text.'
ELSE 'and even more text ''temp'' when
will it stop ?' END)
PRINT 'text don''t text'
PRINT 'text ''test2'' text'
What I want to match is:
PRINT CONVERT(NVARCHAR,
CURRENT_TIMESTAMP, 111) + ' ' +
CONVERT(NVARCHAR, CURRENT_TIMESTAMP,
108)
+ ' -Test Mode : ' + (CASE WHEN #turbo_mode_ind = 1 THEN
'some text ''test''
PRINT 'text ''test2''
So basically I want to match:
starting at PRINT
each char that comes after PRINT (.*)
inclusive line-breaks (don't stop at
line-breaks)
with \'{2}\w+\'{2} at the end of the
match
non-greedy (.*?)
AND no empty line(s) between PRINT
and \'{2}\w+\'{2}
I have already compsed this, but it still matches empty line(s):
PRINT.*?\'{2}\w+\'{2}(?!\n\s*\n)
Edit after comment:
Looking at the requirements again I could not come up with a single regex solution quickly. In your comments you mention that you are using C#.
A possible solution would therfore be to first split the string at blank lines and then extracting the text.
Something like this:
string pattern = #"^$";
foreach (string result in Regex.Split(input, pattern, RegexOptions.Multiline)
{
Regex rxFindSql = Regex(#"PRINT.*?\'{2}\w+?\'{2}", RegexOptions.SingleLine)
MatchCollection matches = rxFindSql.Matches(result);
}
This should do the trick but I did not test the code.
I hope this helps.