case statement in MS Access query give error - ms-access

I am using below query in Ms Access. And this gives me error Syntax error in your query expression CASE WHEN not ... . Can you please tell me what I am doing wrong? In Sql Server 2008 R2, the case statement runs correctly.
SELECT TableApron.RadButtonNo, TableApron.ShortName, QueryForNot1.InspectionDate, QueryForNot1.Findings, QueryForNot1.Status, QueryForNot1.Initials, TableApron.DeptName, TableApron.Lost, TableApron.InServelDate, TableApron.RemovedDate, TableApron.PrivateUserName, TableApron.PrivateUserEmail, TableApron.ApronType, TableApron.Manufacturer
FROM TableApron LEFT JOIN QueryForNot1 ON TableApron.RadButtonNo=QueryForNot1.RadButtonNoI
WHERE (((TableApron.Lost)="N" Or (TableApron.Lost)=[#Lost]) And ((TableApron.InServelDate) Is Null Or (TableApron.InServelDate) Between CDATE([#From]) And CDATE([#To]) Or (TableApron.InServelDate)<CDATE([#To])) And ((TableApron.RemovedDate) Is Null Or (TableApron.RemovedDate) Between CDATE([#From]) And CDATE([#To]) Or (TableApron.RemovedDate)>CDATE([#To])))
ORDER BY
CASE
WHEN not TableApron.RadButtonNo like '%[^0-9]%' THEN CONVERT(int,TableApron.RadButtonNo)
WHEN TableApron.RadButtonNo like '[0-9]%' THEN CONVERT(int,SUBSTRING(TableApron.RadButtonNo,1,PATINDEX('%[A-Z]%',TableApron.RadButtonNo)-1))
END,
CASE
WHEN not TableApron.RadButtonNo like '%[^0-9]%' THEN NULL
WHEN TableApron.RadButtonNo like '[0-9]%' THEN SUBSTRING(TableApron.RadButtonNo,PATINDEX('%[A-Z]%',TableApron.RadButtonNo),9000)
ELSE TableApron.RadButtonNo
END;

The CASE statement triggers the first reported error because it is not supported in Access SQL. Use IIf() instead as #Gustav suggested.
However then you will encounter additional errors because CONVERT, SUBSTRING, and PATINDEX are also not supported in Access SQL.
Instead of CONVERT, use CInt() to cast a value to Access Integer or CLng() for Long Integer. Or you could use Val() and let Access decide which numeric datatype to give you.
Instead of SUBSTRING, use Mid().
Instead of PATINDEX, use InStr().
Assuming those suggestions eliminate the syntax errors, you may still have an issue with the Like wildcard.
If you will be running the query from the query designer or elsewhere under DAO, Access expects * instead of % as the wildcard. % is the correct wild card only when the query is run from ADO/OleDb.

Related

Common Table Expressions -- Using a Variable in the Predicate

I've written a common table expression to return hierarchical information and it seems to work without issue if I hard code a value into the WHERE statement. If I use a variable (even if the variable contains the same information as the hard coded value), I get the error The maximum recursion 100 has been exhausted before statement completion.
This is easier shown with a simple example (note, I haven't included the actual code for the CTE just to keep things clearer. If you think it's useful, I can certainly add it).
This Works
WITH Blder
AS
(-- CODE IS HERE )
SELECT
*
FROM Blder as b
WHERE b.PartNo = 'ABCDE';
This throws the Max Recursion Error
DECLARE #part CHAR(25);
SET #part = 'ABCDE'
WITH Blder
AS
(-- CODE IS HERE )
SELECT
*
FROM Blder as b
WHERE b.PartNo = #part;
Am I missing something silly? Or does the SQL engine handle hardcoded values and parameter values differently in this type of scenario?
Kindly put semicolon at the end of your variable assignment statement
SET #part ='ABCDE';
Your SELECT statement is written incorrectly: the SQL Server Query Optimizer is able to optimize away the potential cycle if fed the literal string, but not when it's fed a variable, which uses the plan that developed from the statistics.
SQL Server 2016 improved on the Query Optimizer, so if you could migrate your DB to SQL Server 2016 or newer, either with the DB compatibility level set to 130 or higher (for SQL Server 2016 and up), or have it kept at 100 (for SQL Server 2008) but with OPTION (USE HINT ('ENABLE_QUERY_OPTIMIZER_HOTFIXES')) added to the bottom of your SELECT statement, you should get the desired result without the max recursion error.
If you are stuck on SQL Server 2008, you could also add OPTION (RECOMPILE) to the bottom of your SELECT statement to create an ad hoc query plan that would be similar to the one that worked correctly.

SSRS casting a parameter to decimal multi select

Im trying to cast a parameter in SSRS to a decimal. I have a in clause since its multi select. I can select 1 and it runs fine however if i select more than 1 it will say
"Incorrect syntax near the keyword 'as'."
I am casting my parameter in my where clause in my query statement.
WHERE LOAD_NO IN (CAST(#Load as DECIMAL))
I am confused as to why it would bring back the syntax error if I select more than one from list.
Thanks
I am confused as to why it would bring back the syntax error if I
select more than one from list.
Short answer
Because WHERE LOAD_NO IN (CAST(1,2,N as DECIMAL)) is not a valid T-SQL statement.
Long answer
When you use a multi-value parameter in a query, reporting services will generate different queries if your parameter contains 1 value, or multiple values.
Let's simplify your example to the following query:
SELECT * FROM TABLE WHERE LOAD_NO IN (#Load)
With only one value, the query will have the following format:
exec sp_executesql N'SELECT * FROM TABLE WHERE LOAD_NO IN (#Load)', N'#Load int', #Load=<YourValue>
It's a query with a parameter: #Load.
Now, with multiple values, the query will become
exec sp_executesql N'SELECT * FROM TABLE WHERE LOAD_NO IN (<YourValue1>, <YourValue2>,<YourValueN>)'
The #Load parameter has been replaced by the list of values.
So now my advise will be to rethink the design of your query and treat #Load as a list of values.
We cannot provide you the best solution because it really depends on the data and only you have all the details but I could still throw some ideas.
On the top of my head I could think of:
Cast LOAD_NO instead, but the execution plan may loose the benefits of indexes if any.
In most cases, using a IF EXISTS when possible instead of IN.
Use a subquery.
Do not hesitate to run a SQL Server Profiler to see the generated query if you have other issues.
I'm not sure what your data looks like, so I'm not sure if these options would help, but here's a couple suggestions:
Try putting the CAST on LOAD_NO instead:
WHERE CAST(LOAD_NO AS VARCHAR) IN (#Load)
Create a splitString function like the accepted post here (T-SQL split string) and access it in your WHERE clause:
WHERE LOAD_NO IN (SELECT CAST(val AS DECIMAL) FROM dbo.splitString(#Load, ','))

Could this simple T-SQL update fail when running on multiple processors?

Assuming that all values of MBR_DTH_DT evaluate to a Date data type other than the value '00000000', could the following UPDATE SQL fail when running on multiple processors if the CAST were performed before the filter by racing threads?
UPDATE a
SET a.[MBR_DTH_DT] = cast(a.[MBR_DTH_DT] as date)
FROM [IPDP_MEMBER_DEMOGRAPHIC_DECBR] a
WHERE a.[MBR_DTH_DT] <> '00000000'
I am trying to find the source of the following error
Error: 2014-01-30 04:42:47.67
Code: 0xC002F210
Source: Execute csp_load_ipdp_member_demographic Execute SQL Task
Description: Executing the query "exec dbo.csp_load_ipdp_member_demographic" failed with the following error: "Conversion failed when converting date and/or time from character string.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
End Error
It could be another UPDATE or INSERT query, but the otehrs in question appear to have data that is proeprly typed from what I see,, so I am left onbly with the above.
No, it simply sounds like you have bad data in the MBR_DTH_DT column, which is VARCHAR but should be a date (once you clean out the bad data).
You can identify those rows using:
SELECT MBR_DTH_DT
FROM dbo.IPDP_MEMBER_DEMOGRAPHIC_DECBR
WHERE ISDATE(MBR_DTH_DT) = 0;
Now, you may only get rows that happen to match the where clause you're using to filter (e.g. MBR_DTH_DT = '00000000').
This has nothing to do with multiple processors, race conditions, etc. It's just that SQL Server can try to perform the cast before it applies the filter.
Randy suggests adding an additional clause, but this is not enough, because the CAST can still happen before any/all filters. You usually work around this by something like this (though it makes absolutely no sense in your case, when everything is the same column):
UPDATE dbo.IPDP_MEMBER_DEMOGRAPHIC_DECBR
SET MBR_DTH_DT = CASE
WHEN ISDATE(MBR_DTH_DT) = 1 THEN CAST(MBR_DTH_DT AS DATE)
ELSE MBR_DTH_DT END
WHERE MBR_DTH_DT <> '00000000';
(I'm not sure why in the question you're using UPDATE alias FROM table AS alias syntax; with a single-table update, this only serves to make the syntax more convoluted.)
However, in this case, this does you absolutely no good; since the target column is a string, you're just trying to convert a string to a date and back to a string again.
The real solution: stop using strings to store dates, and stop using token strings like '00000000' to denote that a date isn't available. Either use a dimension table for your dates or just live with NULL already.
Not likely. Even with multiple processors, there is no guarantee the query will processed in parallel.
Why not try something like this, assuming you're using SQL Server 2012. Even if you're not, you could write a UDF to validate a date like this.
UPDATE a
SET a.[MBR_DTH_DT] = cast(a.[MBR_DTH_DT] as date)
FROM [IPDP_MEMBER_DEMOGRAPHIC_DECBR] a
WHERE a.[MBR_DTH_DT] <> '00000000' And IsDate(MBR_DTH_DT) = 1
Most likely you have bad data are are not aware of it.
Whoops, just checked. IsDate has been available since SQL 2005. So try using it.

Replace IIf with SWITCH in WHERE clause

I have the following query in MS-Access 2003 and it works OK:
SELECT tblDiscounts.DiscountID, tblDiscounts.DiscountPercent, tblDiscounts.DiscountName, tblDiscounts.DiscountDescription
FROM tblDiscounts, qryPropertyPeriodRate_Count_Nested
WHERE (tblDiscounts.DiscountID) = IIf ([qryPropertyPeriodRate_Count_Nested].[CountOfWeeks]=1,1,IIf([qryPropertyPeriodRate_Count_Nested].[CountOfWeeks]=2,2,IIf([qryPropertyPeriodRate_Count_Nested].[CountOfWeeks]=3,3,4)));
I wish to replace the IIf function with the Switch function but whatever I tried didn't work. My best approach is the following:
SELECT tblDiscounts.DiscountID, tblDiscounts.DiscountPercent, tblDiscounts.DiscountName, tblDiscounts.DiscountDescription
FROM tblDiscounts, qryPropertyPeriodRate_Count_Nested
WHERE (((tblDiscounts.DiscountID)=SWITCH ([qryPropertyPeriodRate_Count_Nested].[CountOfWeeks]=1,1, [qryPropertyPeriodRate_Count_Nested].[CountOfWeeks]=2,2, [qryPropertyPeriodRate_Count_Nested].[CountOfWeeks]=3,3, [qryPropertyPeriodRate_Count_Nested].[CountOfWeeks]>3,4)));
but I get a message
Type mismatch in expression
Please advise!
One difference I can see is that if [qryPropertyPeriodRate_Count_Nested].[CountOfWeeks]<1 the nested IIfs will return 4 while the Switch statement will return Null. Check your underlying data to see if that could happen; a Null value might very well mess up the WHERE clause.

NVL2 function does not exist? mysql query

I'm trying to do some queries but I keep getting errors, now I'm thinking that there is something wrong with the mysql installation. Can anybody tell me if there is an error in this query?
SELECT settings.ID,
settings.name,
settings.description,
NVL2(userSettings.value, userSettings.value, settings.default)
FROM settings
LEFT OUTER JOIN userSettings ON (settings.ID = userSettings.settingID)
The error I get says the function databaseX.NVL2 does not exist
I recommend staying away from vendor specific functions when a ANSI standard equivalent alternative is available. NVL and IFNULL for example can (often) be replaced with COALESCE.
You can also use CASE WHEN, which means a lot more typing on the downside, but the upside is that people with background in SQL Server for example won't have to deal with Oracles DECODE() or NVL or NVL2, because the logic is right there in the code.
That's probably because NVL2 is an Oracle function, not a MySQL function. I believe the function you are looking for in MySQL would be COALESCE()
As #Eric Petroelje mentioned NVL2() is Oracle function, not MySQL. However MySQL has its own equivalent that can be used in this case: IFNULL():
SELECT ... IFNULL(userSettings.value, settings.default) ...
After several try&error probes, I found this method to emulate Oracle's NVL2 function. It's not very elegant, but it works
SELECT IF(LENGTH(ISNULL(FieldName, '')) > 0, 'Not NULL Value', 'Null Value') FROM TableName
I think this can help you
IF(expr1,expr2,expr3)
If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2; otherwise it returns expr3. IF() returns a numeric or string value, depending on the context in which it is used.
Alternatively you can substitute NVL2 to:
IF (userSettings.value IS NULL, userSettings.value, settings.default)