Concatenate variable to table element to compare three tables in SQL - sql

I'm using Alpha Anywhere to take a SQL query that my company uses to create a grid.
The query is as follows:
SELECT t.name,cat.description,i.item_num,i.type_of_unit,i.brand,i.pack,i.description2
FROM cim i, tname t, cim cat
WHERE 'P'||i.price_book_code=t.nameid and i.price_book_group=cat.item_num and i.category!=95 and
i.buyer_num!=8 and cat.warehouse_num=0 and i.broken_case != 'Y' and i.item_num not in (select
item_num from proprietary_items)
ORDER BY t.name,cat.description,i.description2, type_of_unit;
In the Where clause, 'P' is concatenated to i.price_book_code to equal t.nameid because all those values have a P at the beginning.
This query works fine in sql-developer, however alpha anywhere will not run it. It claims invalid token at the 'P' level. Apparently this type of concatenation is not compatible to portable SQL. Is there any other way I can concatenate and compare?
Thank you,
Howard

The CONCAT function should work. Here's an example of using it in the WHERE clause:
SELECT *
FROM dual
WHERE CONCAT('Foo','Bar') = 'FooBar';

Related

Convert Legacy to Standard SQL (Join Each and comma Like)

I'm struggling to convert this Legacy SQL Query to Standard SQL. Particular things that need to be converted are FLATTEN, JOIN EACH, No matching signature for function REGEXP_REPLACE for argument types: ARRAY, STRING, STRING. Supported signatures: REGEXP_REPLACE(STRING, STRING, STRING); REGEXP_REPLACE(BYTES, BYTES, BYTES), etc. ...Can anyone please help?
Thanks!
SELECT a.name, b.name, COUNT(*) as count
FROM (FLATTEN(
SELECT GKGRECORDID, UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*'," ")) name
FROM [gdelt-bq:gdeltv2.gkg]
WHERE DATE>20180901000000 and DATE < 20180910000000 and V2Persons like '%Trump%'
,name)) a
JOIN EACH (
SELECT GKGRECORDID, UNIQUE(REGEXP_REPLACE(SPLIT(V2Persons,';'), r',.*'," ")) name
FROM [gdelt-bq:gdeltv2.gkg]
WHERE DATE>20180901000000 and DATE < 20180910000000 and V2Persons like '%Trump%'
) b
ON a.GKGRECORDID=b.GKGRECORDID
WHERE a.name<b.name
GROUP EACH BY 1,2
ORDER BY 3 DESC
LIMIT 250
SELECT a.name, b.b_name, COUNT(*) as count
FROM (
SELECT DISTINCT GKGRECORDID, REGEXP_REPLACE(name, r',.*'," ") name
FROM `gdelt-bq.gdeltv2.gkg`, UNNEST(SPLIT(V2Persons,';')) as name
WHERE DATE>20180901000000 and DATE < 20180910000000 and V2Persons like '%Trump%'
) a
JOIN (
SELECT DISTINCT GKGRECORDID, REGEXP_REPLACE(b_name, r',.*'," ") b_name
FROM `gdelt-bq.gdeltv2.gkg`, UNNEST(SPLIT(V2Persons,';')) as b_name
WHERE DATE>20180901000000 and DATE < 20180910000000 and V2Persons like '%Trump%'
) b
ON a.GKGRECORDID=b.GKGRECORDID
WHERE a.name<b.b_name
GROUP BY 1,2
ORDER BY 3 DESC
LIMIT 250
Re: the flatten I would consult the documentation here: https://cloud.google.com/bigquery/docs/reference/standard-sql/migrating-from-legacy-sql#removing_repetition_with_flatten
Among other examples, the documentation notes:
"Standard SQL does not have a FLATTEN function as in legacy SQL, but you can achieve similar semantics using the JOIN (comma) operator."
Re: Join Each, this has been answered here: BigQuery - equivalent of GROUP EACH in standard SQL
Basically, it is not necessary at all in standard sql
Re: "LIKE that has comma separated parameters...", your syntax is fine for standard sql. it should not operate any differently than it did when you ran in in legacy sql. One of the big pluses of standard sql is that you can compare columns using functions in the WHERE statement with more flexibility than legacy SQL allowed (if necessary). For instance, if you wanted to split V2Persons before running a like comparison, you could do that right in the WHERE statement
UPDATE: Realizing I missed your last question about data type mismatches. In standard sql you will probably want to cast everything explicitly when you run into these errors. It is more finicky than legacy sql with regards to comparisons between different data-types, but I find this to me more in line with other SQL databases.

How to substring records with variable length

I have a table which has a column with doc locations, such as AA/BB/CC/EE
I am trying to get only one of these parts, lets say just the CC part (which has variable length). Until now I've tried as follows:
SELECT RIGHT(doclocation,CHARINDEX('/',REVERSE(doclocation),0)-1)
FROM Table
WHERE doclocation LIKE '%CC %'
But I'm not getting the expected result
Use PARSENAME function like this,
DECLARE #s VARCHAR(100) = 'AA/BB/CC/EE'
SELECT PARSENAME(replace(#s, '/', '.'), 2)
This is painful to do in SQL Server. One method is a series of string operations. I find this simplest using outer apply (unless I need subqueries for a different reason):
select *
from t outer apply
(select stuff(t.doclocation, 1, patindex('%/%/%', t.doclocation), '') as doclocation2) t2 outer apply
(select left(tt.doclocation2), charindex('/', tt.doclocation2) as cc
) t3;
The PARSENAME function is used to get the specified part of an object name, and should not used for this purpose, as it will only parse strings with max 4 objects (see SQL Server PARSENAME documentation at MSDN)
SQL Server 2016 has a new function STRING_SPLIT, but if you don't use SQL Server 2016 you have to fallback on the solutions described here: How do I split a string so I can access item x?
The question is not clear I guess. Can you please specify which value you need? If you need the values after CC, then you can do the CHARINDEX on "CC". Also the query does not seem correct as the string you provided is "AA/BB/CC/EE" which does not have a space between it, but in the query you are searching for space WHERE doclocation LIKE '%CC %'
SELECT SUBSTRING(doclocation,CHARINDEX('CC',doclocation)+2,LEN(doclocation))
FROM Table
WHERE doclocation LIKE '%CC %'

Implement an IN Query using XQuery in MSSQLServer 2005

I'm trying to query an xml column using an IN expression. I have not found a native XQuery way of doing such a query so I have tried two work-arounds:
Implement the IN query as a concatenation of ORs like this:
WHERE Data.exist('/Document/ParentKTMNode[text() = sql:variable("#Param1368320145") or
text() = sql:variable("#Param2043685301") or ...
Implement the IN query with the String fn:contains(...) method like this:
WHERE Data.exist('/Document/Field2[fn:contains(sql:variable("#Param1412022317"), .)]') = 1
Where the given parameter is a (long) string with the values separated by "|"
The problem is that Version 1. doesn't work for more than about 50 arguments. The server throws an out of memory exception. Version 2. works, but is very, very slow.
Has anyone a 3. idea? To phrase the problem more complete: Given a list of values, of any sql native type, select all rows whose xml column has one of the given values at a specific field in the xml.
Try to insert all your parameters in a table and query using sql:column clause:
SELECT Mytable.Column FROM MyTable
CROSS JOIN (SELECT '#Param1' T UNION ALL SELECT '#Param2') B
WHERE Data.exist('/Document/ParentKTMNode[text() = sql:column("T")

Searching a column containing CSV data in a MySQL table for existence of input values

I have a table say, ITEM, in MySQL that stores data as follows:
ID FEATURES
--------------------
1 AB,CD,EF,XY
2 PQ,AC,A3,B3
3 AB,CDE
4 AB1,BC3
--------------------
As an input, I will get a CSV string, something like "AB,PQ". I want to get the records that contain AB or PQ. I realized that we've to write a MySQL function to achieve this. So, if we have this magical function MATCH_ANY defined in MySQL that does this, I would then simply execute an SQL as follows:
select * from ITEM where MATCH_ANY(FEAURES, "AB,PQ") = 0
The above query would return the records 1, 2 and 3.
But I'm running into all sorts of problems while implementing this function as I realized that MySQL doesn't support arrays and there's no simple way to split strings based on a delimiter.
Remodeling the table is the last option for me as it involves lot of issues.
I might also want to execute queries containing multiple MATCH_ANY functions such as:
select * from ITEM where MATCH_ANY(FEATURES, "AB,PQ") = 0 and MATCH_ANY(FEATURES, "CDE")
In the above case, we would get an intersection of records (1, 2, 3) and (3) which would be just 3.
Any help is deeply appreciated.
Thanks
First of all, the database should of course not contain comma separated values, but you are hopefully aware of this already. If the table was normalised, you could easily get the items using a query like:
select distinct i.Itemid
from Item i
inner join ItemFeature f on f.ItemId = i.ItemId
where f.Feature in ('AB', 'PQ')
You can match the strings in the comma separated values, but it's not very efficient:
select Id
from Item
where
instr(concat(',', Features, ','), ',AB,') <> 0 or
instr(concat(',', Features, ','), ',PQ,') <> 0
For all you REGEXP lovers out there, I thought I would add this as a solution:
SELECT * FROM ITEM WHERE FEATURES REGEXP '[[:<:]]AB|PQ[[:>:]]';
and for case sensitivity:
SELECT * FROM ITEM WHERE FEATURES REGEXP BINARY '[[:<:]]AB|PQ[[:>:]]';
For the second query:
SELECT * FROM ITEM WHERE FEATURES REGEXP '[[:<:]]AB|PQ[[:>:]]' AND FEATURES REGEXP '[[:<:]]CDE[[:>:]];
Cheers!
select *
from ITEM where
where CONCAT(',',FEAURES,',') LIKE '%,AB,%'
or CONCAT(',',FEAURES,',') LIKE '%,PQ,%'
or create a custom function to do your MATCH_ANY
Alternatively, consider using RLIKE()
select *
from ITEM
where ','+FEATURES+',' RLIKE ',AB,|,PQ,';
Just a thought:
Does it have to be done in SQL? This is the kind of thing you might normally expect to write in PHP or Python or whatever language you're using to interface with the database.
This approach means you can build your query string using whatever complex logic you need and then just submit a vanilla SQL query, rather than trying to build a procedure in SQL.
Ben

unable to make out use of BETWEEN in oracle

I am not able to make this out: Between eliminates use of >= and <=
...but when i tried this query:
SELECT *
FROM names
WHERE name >= 'Ankit'
AND name <= 'P'
...it gives output:
name
------
Ankit
Mac
Bob
When I tried:
SELECT *
FROM names
WHERE name BETWEEN 'Ankit' AND 'P'
...it gives output:
name
------
Ankit
Can you explain this why?
First, Oracle VARCHAR2 type is case sensitive.
Second, check that you do not have spaces in the beginning of name like this:
" Bob"
" Mac"
Use trim function to check if this causes the problem:
SELECT *
FROM names
WHERE trim(name) BETWEEN 'Ankit' AND 'P'
If this does not help, check that language and sort order are correct for your database.
Edit:
Since above advice did not solve your problem, you could try following:
Maybe you have some other non-printable characters in field. Use Oracle DUMP function to check:
SELECT DUMP(name), name FROM names
You should get something like this:
Typ=1 Len=3: 66,111,98 Bob
...
Verify that Len is correct length.
Check NLS parameters so that they are not inadvertently changed to something that does not work for your database:
SELECT * FROM NLS_SESSION_PARAMETERS
SELECT * FROM NLS_DATABASE_PARAMETERS
SELECT * FROM NLS_INSTANCE_PARAMETERS
Check results of these three queries and verify that parameters on sort, language and character set are correct.
I'm quite certain this has nothing to do with your syntax and everything to do with your DB setup. I've recreated your test scenario and, like others, have no problem with either query returning the results you expect. Did you check your NLS_SESSION_PARAMETERS as mentioned earlier?
SQL code is case insensitive.
String values and string comparisons are case sensitive.
See for yourself:
SELECT CASE WHEN 'a' = 'A' THEN 'string comparison is case insensitive'
WHEN 'a' <> 'A' THEN 'string comparison is case sensitive'
END
FROM dual;
You seem to have used a lowercase 'p' in the top query and an uppercase 'P' in the second. Was this intentional?
SELECT *
FROM names
WHERE name BETWEEN 'Ankit' AND 'P'
also should return all three rows - I just verified that it does so using your example. Are you sure that you made the test correctly? Maybe you inserted data in other session and didn't commit additional rows?
Nut 100% sure about it, but as it's only 3 rows, you could try it:
SELECT *
FROM names
WHERE (name BETWEEN "Ankit" AND "P")
OR (name BETWEEN "ankit" AND "p")