How to make LIKE behave case-insensitive? - abap

I have an importedParameter which I want to search inside of a column in a SELECT.
But for now it is case-sensitive, how can I make it case-insensitive ?
I've tried multiple things: AND LOWER(columnName) LIKE LOWER(#lv_string) or AND columnName LIKE #tst_string COLLATE utf8_general_ci and some other stuff but got this error:
A Boolean expression is required in positions starting with LOWER(Q.
Sample code:
DATA(tst_string) = '%' && importedParamter && '%'.
IF anotherParameter IS NOT INITIAL.
IF importedParamter IS NOT INITIAL.
SELECT * FROM <table1> as p
INNER JOIN <table2> as q on q~column1 = p~column1
WHERE p~column2 = #anotherParameter
AND q~column2 LIKE #tst_string
INTO CORRESPONDING FIELDS OF TABLE #anotherName
ENDIF.
ENDIF.

I believe Regex is your preferred choice: LIKE_REGEXPR:
SELECT *
FROM <table1> as p
INNER JOIN <table2> as q on q~column1 = p~column1
WHERE p~column2 = #anotherParameter
AND like_regexpr( pcre = '\bparam\b', value = q~column2, CASE_SENSITIVE = 'X' ) = '1'
INTO TABLE DATA(#anotherName).
It has CASE_SENSITIVE predicate which respects (or not) the case.
Though this is available only since ABAP 7.55, so on lower releases you are out of the luck.

This code works fine for me:
SELECT *
FROM adrp
WHERE LOWER( name_first ) LIKE 'phi%'
INTO TABLE #DATA(results).
It finds my personal data entry (as well as those of another "Philipp" and of a "Philip"), even though we are all spelled with a capital P.
LIKE LOWER( 'Phi%' ) does not work, but when you can't control the input, then you can convert it to lower case before the select:
DATA(tst_string) = 'Phi%'.
TRANSLATE tst_string TO LOWER CASE.
SELECT *
FROM adrp
WHERE LOWER( name_first ) LIKE #tst_string
INTO TABLE #DATA(results).
Release: 7.54
I am not sure which release specifically allowed functions like LOWER within the WHERE clause. According to the comments, it should work since 7.51.

Related

How to write an Open SQL statement with substring in the JOIN ON condition? [duplicate]

I have the following select statement in ABAP:
SELECT munic~mandt VREFER BIS AB ZZELECDATE ZZCERTDATE CONSYEAR ZDIMO ZZONE_M ZZONE_T USAGE_M USAGE_T M2MC M2MT M2RET EXEMPTMCMT EXEMPRET CHARGEMCMT
INTO corresponding fields of table GT_INSTMUNIC_F
FROM ZCI00_INSTMUNIC AS MUNIC
INNER JOIN EVER AS EV on
MUNIC~POD = EV~VREFER(9).
"where EV~BSTATUS = '14' or EV~BSTATUS = '32'.
My problem with the above statement is that does not recognize the substring/offset operation on the 'ON' clause. If i remove the '(9) then
it recognizes the field, otherwise it gives error:
Field ev~refer is unknown. It is neither in one of the specified tables
nor defined by a "DATA" statement. I have also tried doing something similar in the 'Where' clause, receiving a similar error:
LOOP AT gt_instmunic.
clear wa_gt_instmunic_f.
wa_gt_instmunic_f-mandt = gt_instmunic-mandt.
wa_gt_instmunic_f-bis = gt_instmunic-bis.
wa_gt_instmunic_f-ab = gt_instmunic-ab.
wa_gt_instmunic_f-zzelecdate = gt_instmunic-zzelecdate.
wa_gt_instmunic_f-ZZCERTDATE = gt_instmunic-ZZCERTDATE.
wa_gt_instmunic_f-CONSYEAR = gt_instmunic-CONSYEAR.
wa_gt_instmunic_f-ZDIMO = gt_instmunic-ZDIMO.
wa_gt_instmunic_f-ZZONE_M = gt_instmunic-ZZONE_M.
wa_gt_instmunic_f-ZZONE_T = gt_instmunic-ZZONE_T.
wa_gt_instmunic_f-USAGE_M = gt_instmunic-USAGE_M.
wa_gt_instmunic_f-USAGE_T = gt_instmunic-USAGE_T.
temp_pod = gt_instmunic-pod.
SELECT vrefer
FROM ever
INTO wa_gt_instmunic_f-vrefer
WHERE ( vrefer(9) LIKE temp_pod ). " PROBLEM WITH SUBSTRING
"AND ( BSTATUS = '14' OR BSTATUS = '32' ).
ENDSELECT.
WRITE: / sy-dbcnt.
WRITE: / 'wa is: ', wa_gt_instmunic_f.
WRITE: / 'wa-ever is: ', wa_gt_instmunic_f-vrefer.
APPEND wa_gt_instmunic_f TO gt_instmunic_f.
WRITE: / wa_gt_instmunic_f-vrefer.
ENDLOOP.
itab_size = lines( gt_instmunic_f ).
WRITE: / 'Internal table populated with', itab_size, ' lines'.
The basic task i want to implement is to modify a specific field on one table,
pulling values from another. They have a common field ( pod = vrefer(9) ). Thanks in advance for your time.
If you are on a late enough NetWeaver version, it works on 7.51, you can use the OpenSQL function LEFT or SUBSTRING. Your query would look something like:
SELECT munic~mandt VREFER BIS AB ZZELECDATE ZZCERTDATE CONSYEAR ZDIMO ZZONE_M ZZONE_T USAGE_M USAGE_T M2MC M2MT M2RET EXEMPTMCMT EXEMPRET CHARGEMCMT
FROM ZCI00_INSTMUNIC AS MUNIC
INNER JOIN ever AS ev
ON MUNIC~POD EQ LEFT( EV~VREFER, 9 )
INTO corresponding fields of table GT_INSTMUNIC_F.
Note that the INTO clause needs to move to the end of the command as well.
field(9) is a subset operation that is processed by the ABAP environment and can not be translated into a database-level SQL statement (at least not at the moment, but I'd be surprised if it ever will be). Your best bet is either to select the datasets separately and merge them manually (if both are approximately equally large) or pre-select one and use a FAE/IN clause.
They have a common field ( pod = vrefer(9) )
This is a wrong assumption, because they both are not fields, but a field an other thing.
If you really need to do that task through SQL, I'll suggest you to check native SQL sentences like SUBSTRING and check if you can manage to use them within an EXEC_SQL or (better) the CL_SQL* classes.

An object or column name is missing or empty. But its not?

I am on the 7th set of queries I have been working on and all of them have used SELECT * INTO some_table without an issue. For some reason tho the below query in SQL Server is throwing the error
An object or column name is missing or empty. For SELECT INTO
statements, verify each column has a name. For other statements, look
for empty alias names. Aliases defined as "" or [] are not allowed.
Change the alias to a valid name.
Any Idea on what it could be?
Note that running the query without the select into will result in data being returned and displayed as expected.
Select * into MYDB.MY_TBL
SELECT OT.U_ID AS "U_ID"
,R.E AS "E"
,R.IR AS "CKT"
,A.RI AS "OC"
,A.EQ AS "SEQ"
,A.HA AS "CHA"
,A.A_HA AS "ATE"
,A.BIL AS "BIL"
,A.CHA AS "CHAA"
,A.RAT AS "AMT"
,A.PRM AS "PREM"
,A.T_CHG AS "RAT"
,A.PER AS "LAS"
,A.S_BIL AS "BIL_A"
,A.CD AS "CDE"
,A.CBIL_J AS "BIL_J"
,A.AMT_D AS "TB"
,A.CRY AS "CTRY"
,A.RVW AS "RVW"
FROM MYDB.OTHER_TBL OT
JOIN [LINKEDSERVER\INST,0000].FE.dbo.tblR R
ON OT.E = R.E
JOIN [LINKEDSERVER\INST,0000].FE.dbo.tblA A
ON R.IR = A.IR
WHERE OT.U_ID = 'TEST'
You have two selects. I think you just want:
SELECT OT.U_ID AS "U_ID",
. . .
INTO MYDB.MY_TBL
FROM . . .
The INTO should follow the SELECT column list.
Or alternatively, you could use a subquery, but that does not seem necessary.
Where #GordonLinoff example works I realized what I forgot and it was my FROM () sub-query setup I normally use.
I will provide an example in contrast to Gordon's method.
IE:
Select * into MYDB.MY_TBL
FROM(
SELECT OT.U_ID AS "U_ID"
...
FROM MYDB.OTHER_TBL OT
WHERE OT.U_ID = 'TEST'
) SUB
Please note these two points:
1.You have two columns with given "CHA" alias
2.It Seems you need to rewrite the query as:
SELECT OT.U_ID AS "U_ID"
,R.E AS "E"
,R.IR AS "CKT"
,A.RI AS "OC"
,A.EQ AS "SEQ"
,A.HA AS "CHA_DUPLICATE"
,A.A_HA AS "ATE"
,A.BIL AS "BIL"
,A.CHA AS "CHA_DUPLICATE2"
,A.RAT AS "AMT"
,A.PRM AS "PREM"
,A.T_CHG AS "RAT"
,A.PER AS "LAS"
,A.S_BIL AS "BIL_A"
,A.CD AS "CDE"
,A.CBIL_J AS "BIL_J"
,A.AMT_D AS "TB"
,A.CRY AS "CTRY"
,A.RVW AS "RVW"
INTO MYDB.MY_TBL -- <<<<<<< NOTE
FROM MYDB.OTHER_TBL OT
JOIN [LINKEDSERVER\INST,0000].FE.dbo.tblR R
ON OT.E = R.E
JOIN [LINKEDSERVER\INST,0000].FE.dbo.tblA A
ON R.IR = A.IR
WHERE OT.U_ID = 'TEST'

Error in select statement, with union all in a subquery

In Oracle 11g, I came across an error for a query and cannot figure why it is erroring on me. Here is the query:
select
main_data.issue_number,
main_data.transaction_number
from
(
select
p1.payment_date,
p1.media_number,
p1.payment_amount,
p1.issue_number,
p1.advice_na_number,
name.name_address_line_1,
name.name_address_line_2,
name.name_address_line_3,
name.name_address_line_4,
name.name_address_line_5,
name.name_address_line_6,
name.name_address_line_7,
name.name_address_city,
name.state_code,
name.address_country_code,
name.zip_code,
name.tax_id_number,
p1.output_tx_number_prin,
p1.output_tx_number_int,
'' as "transaction_number",
p1header.check_account_number
from
p1
left join name on p1.name_address_number = name.name_address_number
left join p1header on p1.issue_number = p1header.issue_number
UNION ALL
select
check.date_of_payment,
check.media_number,
check.payment_amount,
check.issue_number,
check.payee_na_number,
name.name_address_line_1,
name.name_address_line_2,
name.name_address_line_3,
name.name_address_line_4,
name.name_address_line_5,
name.name_address_line_6,
name.name_address_line_7,
name.name_address_city,
name.state_code,
name.address_country_code,
name.zip_code,
name.tax_id_number,
'' as "output_tx_number_prin",
'' as "output_tx_number_int",
check.transaction_number,
check.dda_number as "check_account_number"
from check
left join name on check.payee_na_number = name.name_address_number
) main_data
Selecting individual fields like above will give me an "invalid identifier error". If I do select * then it gives me back the data without any error. What am I doing wrong here? Thank you.
The old quoted identifier problem... see point 9 in the database object naming documentation, and note that Oracle does not recommend using quoted identifiers.
You've put your column alias as lower case inside double-quotes. That means that any references to it also have to be quoted and exactly match the case. So this would work:
select
main_data.issue_number,
main_data."transaction_number"
from
...
But unless you have a burning need to have that alias like that - and I doubt you do as all the identifier names from the actual table columns are not quoted - it would be simpler to remove the double quotes from the inner selects:
select
main_data.issue_number,
main_data.transaction_number
from
(
select
...
'' as transaction_number,
p1header.check_account_number
...
UNION ALL
select
...
'' as output_tx_number_prin,
'' as output_tx_number_int,
check.transaction_number,
check.dda_number as check_account_number
...
You don't actually need to alias the columns in the second branch of the union; the column identifiers will all be taken from the first branch.

Return 0 if field is null in MySQL

In MySQL, is there a way to set the "total" fields to zero if they are NULL?
Here is what I have:
SELECT uo.order_id, uo.order_total, uo.order_status,
(SELECT SUM(uop.price * uop.qty)
FROM uc_order_products uop
WHERE uo.order_id = uop.order_id
) AS products_subtotal,
(SELECT SUM(upr.amount)
FROM uc_payment_receipts upr
WHERE uo.order_id = upr.order_id
) AS payment_received,
(SELECT SUM(uoli.amount)
FROM uc_order_line_items uoli
WHERE uo.order_id = uoli.order_id
) AS line_item_subtotal
FROM uc_orders uo
WHERE uo.order_status NOT IN ("future", "canceled")
AND uo.uid = 4172;
The data comes out fine, except the NULL fields should be 0.
How can I return 0 for NULL in MySQL?
Use IFNULL:
IFNULL(expr1, 0)
From the documentation:
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.
You can use coalesce(column_name,0) instead of just column_name. The coalesce function returns the first non-NULL value in the list.
I should mention that per-row functions like this are usually problematic for scalability. If you think your database may get to be a decent size, it's often better to use extra columns and triggers to move the cost from the select to the insert/update.
This amortises the cost assuming your database is read more often than written (and most of them are).
None of the above answers were complete for me.
If your field is named field, so the selector should be the following one:
IFNULL(`field`,0) AS field
For example in a SELECT query:
SELECT IFNULL(`field`,0) AS field, `otherfield` FROM `mytable`
Hope this can help someone to not waste time.
You can try something like this
IFNULL(NULLIF(X, '' ), 0)
Attribute X is assumed to be empty if it is an empty String, so after that you can declare as a zero instead of last value. In another case, it would remain its original value.
Anyway, just to give another way to do that.
Yes IFNULL function will be working to achieve your desired result.
SELECT uo.order_id, uo.order_total, uo.order_status,
(SELECT IFNULL(SUM(uop.price * uop.qty),0)
FROM uc_order_products uop
WHERE uo.order_id = uop.order_id
) AS products_subtotal,
(SELECT IFNULL(SUM(upr.amount),0)
FROM uc_payment_receipts upr
WHERE uo.order_id = upr.order_id
) AS payment_received,
(SELECT IFNULL(SUM(uoli.amount),0)
FROM uc_order_line_items uoli
WHERE uo.order_id = uoli.order_id
) AS line_item_subtotal
FROM uc_orders uo
WHERE uo.order_status NOT IN ("future", "canceled")
AND uo.uid = 4172;

T-SQL - Aliasing using "=" versus "as" [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Is there any particular reason (performance or otherwise) to use AS ahead of = when aliasing a column?
My current approach (for readability) is to use this:
select
alias1 = somecolumn
alias2 = anothercolumn
from
tables
etc...
instead of this:
select
somecolumn as alias1
anothercolumn as alias2
from
tables
etc...
Is there a performance or maintainability reason to use one over the other?
‘=’ isn't valid ANSI SQL, so you'll have difficulty should you wish to run your application on a different DBMS.
(It's when ANSI form is used but the optional ‘AS’ is omitted I find the results difficult to read, personally.)
To put in some counterweight, I prefer using =.
If I am the consumer of the query results in some way, I find it more convenient to see what columns I as a consumer can use.
I prefer this
SELECT
[ElementObligationID] = #MaxElementObligationID + eo.ElementObligationID
, [ElementID] = eo.ElementID
, [IsotopeID] = eo.IsotopeID
, [ObligationID] = eo.ObligationID
, [ElementWeight] = eo.ElementWeight * -1
, [FissileWeight] = eo.FissileWeight * -1
, [Items] = eo.Items * -1
, [Comment] = eo.Comment
, [AdditionalComment] = eo.AdditionalComment
, [Aanmaak_userid] = #UserID
, [Aanmaak_tijdstip] = GetDate()
, [Laatste_wijziging_userid] = #UserID
, [Laatste_wijziging_tijdstip] = GetDate()
FROM dbo.KTM_ElementObligation eo
INNER JOIN dbo.KTM_ElementObligationArticle eoa ON
eoa.ElementObligationID = eo.ElementObligationID
over this
SELECT
#MaxElementObligationID + eo.ElementObligationID AS [ElementObligationID]
, eo.ElementID AS [ElementID]
, eo.IsotopeID AS [IsotopeID]
, eo.ObligationID AS [ObligationID]
, eo.ElementWeight * -1 AS [ElementWeight]
, eo.FissileWeight * -1 AS [FissileWeight]
, eo.Items * -1 AS [Items]
, eo.Comment AS [Comment]
, eo.AdditionalComment AS [AdditionalComment]
, #UserID AS [Aanmaak_userid]
, GetDate() AS [Aanmaak_tijdstip]
, #UserID AS [Laatste_wijziging_userid]
, GetDate() AS [Laatste_wijziging_tijdstip]
FROM dbo.KTM_ElementObligation eo
INNER JOIN dbo.KTM_ElementObligationArticle eoa ON
eoa.ElementObligationID = eo.ElementObligationID
just my 2c.
I wouldn't use it simply as it looks far too much like equality operation. 'AS' is clear inasmuch that it's not ambiguous to me.
Its the same as not using upper case in sql, I find it harder to read.
I'm not as lucky as others who have posted here. The code I work with is usually written by someone else and it is rare that there are not CASE statements or other calculations, concatenations or logic that cause a single entry to span over several rows of T_SQL script.
Using a equal sign instead of 'AS' is by far easier to read. With an equal sign you know the alias name you are looking for is in the first position of the row. When 'AS' is used and the T_SQL spans multiple lines, the alias name could literally be anywhere.
It is far, far, far easier to find the 'Items' alias when equals is used than when 'AS' is used.
SELECT
ElementObligationID = #MaxElementObligationID + eo.ElementObligationID
, ElementID = eo.ElementID
, IsotopeID = eo.IsotopeID
, ObligationID = eo.ObligationID
, ElementWeight = eo.ElementWeight * -1
, FissileWeight = eo.FissileWeight * -1
, Items = CASE WHEN eo.Items < 0 THEN eo.Items * -1
WHEN eo.Items > 0 THEN eo.Items
ELSE 0 END
, Comment = eo.Comment
, AdditionalComment = eo.AdditionalComment
, Aanmaak_userid = #UserID
, Aanmaak_tijdstip = GetDate()
, Laatste_wijziging_userid = #UserID
, Laatste_wijziging_tijdstip = GetDate()
FROM dbo.KTM_ElementObligation eo
INNER JOIN dbo.KTM_ElementObligationArticle eoa ON
eoa.ElementObligationID = eo.ElementObligationID
Now imagine having more than 5 times the amount of code that is here and needing to find the 'Items' alias.
SELECT
#MaxElementObligationID + eo.ElementObligationID AS ElementObligationID
, eo.ElementID AS ElementID
, eo.IsotopeID AS IsotopeID
, eo.ObligationID AS ObligationID
, eo.ElementWeight * -1 AS ElementWeight
, eo.FissileWeight * -1 AS FissileWeight
, CASE WHEN eo.Items < 0 THEN eo.Items * -1
WHEN eo.Items > 0 THEN eo.Items
ELSE 0 END AS Items
, eo.Comment AS Comment
, eo.AdditionalComment AS AdditionalComment
, #UserID AS Aanmaak_userid
, GetDate() AS Aanmaak_tijdstip
, #UserID AS Laatste_wijziging_userid
, GetDate() AS Laatste_wijziging_tijdstip
FROM dbo.KTM_ElementObligation eo
INNER JOIN dbo.KTM_ElementObligationArticle eoa ON
eoa.ElementObligationID = eo.ElementObligationID
'AS' vs '=' is not a capricious and arbitrary preference. I am not exaggerating when I say there have been times when it would take several minutes to find the alias name I am looking for because the author of the script I am now in charge of maintaining did not use the equals sign with their alias. I cannot think of a bigger waste of time, money and resources than paying an IT professional to look for alias names in code!! There is a right and wrong answer if you care about maintainability, readability, and efficiency. Your job is to provide business value, not to spend your day looking for Waldo!
"=" is just plain ambiguous.
If you indent to break out each select clause...
select
alias1 = somecolumn,
alias2 = anothercolumn,
result = column1 * column2
from
table
....
select
somecolumn as alias1,
anothercolumn as alias2,
column1 * column2 as result
from
tables
...
= can be confused with assignment and equality; actually, the form I really don't like is when it looks like a string (usually when spaces are involved):
somecolumn as 'alias 1'
or
'alias 1' = somecolumn
I far prefer the alternative notation:
somecolumn as [alias 1]
The postfix alias form (with or without the "AS") is consistent between column and table aliases. Personally, I'd like an option to enforce the use of "AS", and then you wouldn't have the situation:
select
columnA,
columnB
columnC
from
table
producing a result set with two columns instead of the expected 3.
I'd also say that with the prefix "=" form, it can make it more difficult to read if you're mixing obtaining a result set and variable assignment:
select
cA = columnA,
#cB = columnB,
cC = columnC
from
table
The three ways I know of to alias:
TableColumn AS MyAlias
TableColumn MyAlias
MyAlias = TableColumn
Re: 1), I prefer this as it is the most self-documenting code (IMO), and it lets me search for AS if I need to find aliases..
Re: 2), This is my second choice, but without the AS, I am never sure whether this is a cut-and-paste error or not, especially in long, badly-formatted queries.
Re: 3), I don't like this because a) it looks like an assignment, and b) it blends in too much with ON clauses and CASE statements
So, my vote is to use the AS keyword for your aliases.
I prefer using AS since = is used in the where statement, and can be confusing in a long query.
I prefer using neither of those. I just give the name of the column without any keyword in between
SELECT MAX(price_column) maximumprice FROM prices
Column aliases declared by "=" syntax are deprecated in SQL Server 2008 and not supported in the next version. See MSDN article.
While I have a preference for using AS, the really key thing here is to have a corporate standard and to follow it. If more of your people use AS than = then everyone should use it. Coding standards are what makes it easier to maintain code not the particular standard you pick. If everyone uses the same thing, then your eye gets used to picking it out.
I like the
SELECT
column1 = table.column1
,column2 = table.colum2
FROM table
I find AS not as easily noticable compared to a = sign (I can spot = quicker than AS)
Also when one just does SELECT column alias, sometimes it's confusing to know which one is which :)
Since I write SQL for several different relational database management systems, I prefer to use a syntax which works on all of them, which normally means writing ANSI compatible SQL. My normal formatting preference is:
SELECT
S.name AS SchemaName,
O.name AS ObjectName,
C.column_id AS ColumnId,
C.name AS ColumnName
FROM
sys.schemas AS S
INNER JOIN sys.objects AS O ON S.schema_id = O.schema_id
INNER JOIN sys.columns AS C ON O.object_id = C.object_id
ORDER BY
S.name ASC,
O.name ASC,
C.column_id ASC;
As an alternative formatting of the above, the following makes it easier to see the column alias names:
SELECT
S.name
AS SchemaName,
O.name
AS ObjectName,
C.column_id
AS ColumnId,
C.name
AS ColumnName
FROM
sys.schemas AS S
INNER JOIN sys.objects AS O ON S.schema_id = O.schema_id
INNER JOIN sys.columns AS C ON O.object_id = C.object_id
ORDER BY
S.name ASC,
O.name ASC,
C.column_id ASC;
**even i prefer using 'as' instead of '=' . '=' makes confusion in code.
e.g :
column as alias1
You don't have to use either
Drop the AS and use
SELECT originalname alias
FROM
tablename