Incorrect syntax near '.' - very simple query - sql-server-2000

I have very simple query that calls a UDF which splits a field by comma. The query is
select top 10 * FROM Emails e WHERE EXISTS(SELECT TOP 1 1 FROM dbo.fn_Split(e.committees,','))
When I run/parse it, I get:
Msg 170, Level 15, State 1, Line 4
Line 4: Incorrect syntax near '.'.
I think it must have something to do with SQL 2000. If you switch out e.committees for something hardcoded (i.e., 'A,B,C,D') it works fine.

SQL 2000 doesn't support passing column names to TVFs. That was brought in in SQL2005 along with CROSS APPLY
I'm not really sure what you are needing to do here. Is e.committees a non 1NF list of numeric committee ids? If so
select top 10 <column-list>
FROM Emails e
WHERE e.committees
like '%[0-9]%'
ORDER BY ...
Might work but a better solution would be to store these in a normalised form in a table with columns email_id,committee_id or whatever. This will likely make your queries easier!

Related

How to get average of multiple variables

Table name: products,
column names: rice_price, sugar_price
I would like to get the average of both columns separately. For example;
SELECT
AVG(rice_price) avg_rice,
AVG(sugar_price) avg_sugar
FROM
products
If I run this query on SQL server, I get the message below
Msg 8117, Level 16, State 1, Line 4
Operand data type nvarchar is invalid for avg operator.
What could be the solution?
If most of them look like numbers, you could use this, which will exclude the ones that don't convert nicely, by handling them as null:
SELECT
AVG(try_convert(numeric(18,4),rice_price)) avg_rice,
AVG(try_convert(numeric(18,4),sugar_price)) avg_sugar
FROM
products
But you should be changing your datatypes as has been pointed out in the comments. This kind of query will help you discover the ones that aren't good.
SELECT *
FROM products
WHERE rice_price IS NOT NULL
AND try_convert(numeric(18,4),rice_price) IS NULL
SELECT *
FROM products
WHERE sugar_price IS NOT NULL
AND try_convert(numeric(18,4),sugar_price) IS NULL
The IS_NUMERIC function can work for this too, but I find I have switched to using TRY_CONVERT in this situation, because it feels more flexible - I can use whatever data type I need.

Check if string is found in one of multiple columns in SQL

I want to search a string in multiple columns to check if it exists in any.
I found a solution for it here
The answer by Thorsten is short but that is a solution for mysql server not for SQL Server.
So I would like to apply similar query in SQL Server.
Here is the query suggested by Thorsten.
Select *
from tblClients
WHERE name || surname LIKE '%john%'
I tried it as
/* This returns nothing */
Select *
from Items
Where ISNULL(Code, '') + ISNULL(Code1, '') = '6922896068701';
Go
/* This generate error Msg 102, Level 15, State 1, Line 3
Incorrect syntax near '|'.
I also used this one in mysql but it does not show the exact match.
*/
Select *
from Items
WHERE Code || Code1 = '6922896068701';
Go
/* This generate error Msg 4145, Level 15, State 1, Line 5
An expression of non-boolean type specified in a context where a condition is expected, near 'Or'. */
Select *
from Items
WHERE Code Or Code1 = '6922896068701';
Go
Is it really possible in SQL Server?
Note: The answer by J__ works accurately in the upper Question link but I want the comparison string to be entered once for all columns where I look for it like Thorsten.
Actually I think that separate logical checks in the WHERE clause for each column is the way to go here. If you can't do that for some reason, consider using a WHERE IN (...) clause:
SELECT *
FROM Items
WHERE '6922896068701' IN (Code, Code1);
If instead you want LIKE logic, then it gets tricky. If you knew that the matching codes would always consist of numbers/letters, then you could try:
SELECT *
FROM Items
WHERE ',' + Code + ',' + Code1 + ',' LIKE '%,6922896068701,%';
I would recommend doing the two comparisons separately:
WHERE name LIKE '%john%' OR
surname LIKE '%john%'
Unless you specifically want to find times when the names are combined, such as "Maryjoh" "Needlebaum" or whatever.
It is generally better to focus on one column at a time, because that helps the optimizer.
For MS SQL this may work;
Select *
from Items
WHERE Code = '6922896068701' Or Code1 = '6922896068701'

Need 8 characters form a lengthy RegKey path - Invalid length parameter passed to the LEFT or SUBSTRING

I have been working with a guy to finish off a rather ingenious means by which to extract information on packages installed by SCCM 2012 vs the built-in inventoried "Programs and Features". The last piece is extracting the PACKAGEID from registry strings that have been inventoried in the aforementioned process. Each string looks like this (the target "PACKAGEID" is identified in bold:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SMS\Mobile Client\Software Distribution\Execution History\System\ LAB00003 \ac80c725-7dc7-11e5-9bc8-000c292d4525
As stated, i am not the genius behind any of this but i wanted to understand why i am getting the following error:
Msg 537, Level 16, State 3, Line 1
Invalid length parameter passed to the LEFT or SUBSTRING function.
From the following query:
SELECT
DataType0,
KeyPath0,
Name0,
Value0,
(
SELECT SUBSTRING(KeyPath0, LEN(LEFT(KeyPath0, CHARINDEX ('\System\', KeyPath0))) + 1, LEN(KeyPath0) - LEN(LEFT(KeyPath0, CHARINDEX ('\System\', KeyPath0))) - LEN(RIGHT(KeyPath0, LEN(KeyPath0) - CHARINDEX ('\', KeyPath0))) - 1)
) as "Package ID"
FROM
dbo.v_GS_Registry_Values0
i verified that the the dbo.v_GS_Registry_Values0 view does indeed have the reg key string in it via select * from SCCM_Ext.vex_GS_Registry_Values0 but despite tons of searching, my simple sql mind cannot make sense of the query and its use of LEN & CHARINDEX.
Totally throwing myself at the mercy of this site in hopes i could get not only the resolution to this but also a better understanding of why this is happening and how the query works.
if there is ANY additional information i could provide please let me know.
If you're just trying to get the next string after \System\ you're SQL is quite complex, you can do it just with this:
SELECT left (Y.S, charindex ('\', Y.S) - 1)
from Table1
outer apply (
select CHARINDEX ('\System\', KeyPath0) as pos
) X
outer apply (
select substring (KeyPath0, X.pos + 8, 9999) as S
) Y
Example in SQL Fiddle
The first outer apply finds the \System\ the second gets the rest of the string (assuming max path is 9999 characters) and then just take the part before the next \ in the actual select.

Checking for a Substring in [Field] within Case Statement for Oracle PL/SQL?

I'm writing an Oracle Database Conversion script to move records (roughly 1,300) from an old DB table to a more standardized setup with a main table and several child/reference/maintenance tables. One situation I'm dealing with is where (in the old setup) several records contain [Status] values such as RECYCLED under the [Location] field. I've gone through using a Case statement to get the basics as below:
WHEN RTRIM(LTRIM(Vendor_Name)) in (
'EDAC') THEN 23 END as VendorID,
CASE
WHEN RTRIM(LTRIM(LOCATION)) in (
'Auctioned') THEN 3
WHEN RTRIM(LTRIM(LOCATION)) in (
'Recycled') THEN 5
WHEN RTRIM(LTRIM(LOCATION)) in (
'To Be Recycled') THEN 6
WHEN RTRIM(LTRIM(LOCATION)) in (
'DISPOSED OF') THEN 7
WHEN RTRIM(LTRIM(LOCATION)) in (
'To Be Auctioned') THEN 4
There are however a few variations with extra text (and variations OF the extra text) such as 'To be auctioned, SERVER ROOM'. I'm trying to figure out how to do something like a CONTAINS or LIKE check within my case statement, so like in the mentioned CONTAINS ('%To be auctioned%') THEN 42.
Can anyone provide an easy to understand example? I've reviewed the Oracle documentation, but I'm not fully understanding the Index portion or how exactly to specify what I'm after in proper syntax - http://www.dba-oracle.com/t_sql_contains_clause.htm.
Try:
when location like '%To be auctioned%' then 4
You have to account for upper and lower case, and sometimes accented characters.
é anyone?
WHEN instr(UPPER(LOCATION)),'AUCTION') > 0 THEN 4
To account for words with accents you need to use REPLACE to change é to e and then compare

Issues when using SUBSTRING to trim the first 6 characters in SQL Server

I have a table named Articles, which suprisingly has a column named Article, which is the Primary Key.
In this column all articles used to be designated with an unnecessary prefix which I am tasked to remove.
Examples:
1-184-W21TK00032
1-154-MXA0074
In these examples both 184 and 154 designate distributors, they all have a few thousand Articles in this table.
I encountered zero problems when running this query:
UPDATE Articles
SET Article = SUBSTRING(Article,7,LEN(Article)-6)
WHERE SUBSTRING(Article,3,3) = '184'
I was unable to run this query without a WHERE designation. I altered the final line to switch to the next distributor: 154
WHERE SUBSTRING(Article,3,3) = '154'
And ran into this error:
Msg 536, Level 16, State 5, Line 1
Invalid length parameter passed to the SUBSTRING function.
I have also tried using LIKE in the WHERE line, to designate everything using '-154-' like so
WHERE Article LIKE '_-154-%'
but this would inexplicably lead to this, as would running the query without a WHERE as I started out trying:
Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'aaaaaArticles_PK'. Cannot insert duplicate key in object 'dbo.Articles'.
Any ideas or suggestions? I'm at a loss. Running it without a WHERE line is now impossible for the thousands of products using 184 have succesfully been altered.
The problem occurs because LEN(Article) is less than 6 for at least 1 row which means you are passing a negative value into the SUBSTRING. Filter them out using WHERE LEN(Article) > 6
It's probably not the WHERE you're changing that is the issue.
There are probably rows for "154" where the other SUBSTRING fails.
That is, there are probably (Len(Article) - 6) < 0.
Search for that to confirm and then add a CASE or such to manage it.
Try:
RIGHT(article,LEN(article)-6)
Instead of Substring, this will select everything to the right of the first 6 characters.